亂碼問題,網上找了找,各種版本,現在發現,各種的經驗遍地開。。。
不多說,成功的方式如下:
1.設定好各處的頁面編碼,我一直都設定成了utf-8,沒見什麼異常;
2.ajax 處理方式,見源碼
$.ajax({type : "POST",contentType : "application/json",url : "ToHistoryServlet?handleFlag=add&sendPerson=" + sendPerson+ "¤tTime=" + currentTime() + "&message="+ encodeURIComponent(message) + "&recvPerson=" + recvPerson,dataType : 'json',success : function(result) {alert(result.d);}});
注意事項:a.使用POST方式;
b.中文前加encodeURIComponent(把字串編碼為URI組件);
c.本例應用了jQuery。
3.servlet接收時處理方式,見源碼
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");String handleFlag = request.getParameter("handleFlag");Message msg = new Message();// handle chinese code dml@2012.8.29if (request.getParameter("message") != null) {msg.setMessage(new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8"));}msg.setRecvPerson(request.getParameter("recvPerson"));msg.setSendPerson(request.getParameter("sendPerson"));msg.setSendTime(request.getParameter("currentTime"));if (handleFlag.equals("add")) {HistoryHandle.addMessage(msg);} else if (handleFlag.equals("delete")) {HistoryHandle.deleteMessage(msg);}}
注意事項:a.設定編碼方式 request.setCharacterEncoding為utf-8;
b.js預設的編碼是iso8859-1,所以需要轉換一下
String xxxxx=new String(request.getParameter("message").getBytes("iso8859-1"), "UTF-8")
如上操作即可解決ajax亂碼問題。