用 jQuery 的 ajax 提交含中文的數據,後台收到的卻是亂碼——這是早期 Java Web 開發中最常見的坑之一。下面把成因和解法系統梳理一遍。
$.ajax({
dataType: 'json',
type: 'POST',
url: 'https://localhost/test/test.do',
data: { id: 1, type: '商品' },
success: function(data) { }
});
提交後後台 action 取到的 type 是亂碼。
注意一定是兩次編碼:
data: { id: 1, type: encodeURI(encodeURI('商品')) }
後台 action 中再解碼:
String type = request.getParameter("type");
type = URLDecoder.decode(type, "UTF-8");
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
關鍵在於 charset=UTF-8 這一段。其他 JS 框架或直接用 XHR 也是同樣思路——設置 header 中的 contentType 即可。如果少了 charset,是不會生效的;jQuery 默認的 contentType 裡並沒有它。
測試環境:jQuery 1.3.2、Tomcat 5.5.17。
服務端:
String name = new String(request.getParameter("name").getBytes("iso8859-1"), "utf-8");
客戶端與結果對照:
$.ajax({ url: "2.jsp", type: "get", data: { name: "中文" }, success: ... });
// 結果:正確顯示
$.ajax({ url: "2.jsp", type: "get", data: "name=中文", success: ... });
// 結果:亂碼
$.get("2.jsp", { name: "中文" }, function(response) { ... });
// 結果:正確顯示
$.get("2.jsp", "name=中文", function(response) { ... });
// 結果:亂碼
規律很清晰:傳對象時 jQuery 會自動 encodeURI,傳字符串時不會。這就是差異的根源。
服務端:
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
客戶端四種寫法全部正確顯示:
$.ajax({ url: "3.jsp", type: "post", data: "method=testAjaxPost&name=中文", success: ... });
$.ajax({ url: "3.jsp", type: "post", data: { name: "中文" }, success: ... });
$.post("3.jsp", { name: "中文" }, function(response) { ... });
$.post("3.jsp", "name=中文", function(response) { ... });
POST 之所以沒問題,是因為瀏覽器提交表單時默認按 UTF-8 編碼表單數據,只要服務端用 setCharacterEncoding("UTF-8") 對齊即可。
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getHeader("X-Requested-With") != null &&
req.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
request.setCharacterEncoding("utf-8");
} else {
request.setCharacterEncoding("gbk");
}
chain.doFilter(request, response);
}
原理:jQuery 使用 ajax 時會在 header 中加入 X-Requested-With: XMLHttpRequest。Filter 中判斷到這個標記,就把編碼設為 UTF-8,否則沿用 GBK。這樣既能解決 ajax POST 的中文亂碼,又不必在每個 action 裡重複寫 setCharacterEncoding,也不影響頁面表單的正常提交。
為了和 prototype.js 的處理方式保持一致,可以自定義一個 RequestType 頭:
$.ajax({
url: "3.jsp",
type: "post",
data: { name: "中文" },
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("RequestType", "ajax");
},
success: function(data, textStatus) { alert(data); },
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("錯誤:" + textStatus);
},
complete: function(XMLHttpRequest, textStatus) {
alert("完成:" + textStatus);
}
});
對應的 Filter:
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
if (req.getHeader("RequestType") != null &&
req.getHeader("RequestType").equalsIgnoreCase("ajax")) {
request.setCharacterEncoding("utf-8");
} else {
request.setCharacterEncoding("gbk");
}
chain.doFilter(request, response);
}