Ajax 的中文問題大致可以分成兩類:一類出在送出去的參數,一類出在收回來的內容。搞清楚了方向,修起來就很快。
例如:
var url = "a.jsp?name=小李";
xmlHTTP.open("post", url, true);
解法:利用 JavaScript 提供的 escape() 或 encodeURI() 先把中文編碼。
// 用戶端
var url = "a.jsp?name=小李";
url = encodeURI(url);
url = encodeURI(url); // 編兩次,這一點很關鍵
// 也有人寫成
var url = "a.jsp?name=" + escape("小李");
兩種寫法效果相近。接著設定請求標頭:
xmlHTTP.setRequestHeader("cache-control", "no-cache");
xmlHTTP.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHTTP.setRequestHeader("contentType", "text/html;charset=utf-8"); // 指定送出資料的編碼
xmlHTTP.open("post", url, true);
伺服器端則要對應解碼:
String name = request.getParameter("name");
name = java.net.URLDecoder.decode(name, "UTF-8");
原因:Ajax 在接收 responseText 或 responseXML 時是按 UTF-8 解碼的。如果伺服器送出的資料不是 UTF-8,取到的值自然就亂了。
解法:在伺服器端明確指定輸出編碼。
// 回傳純文字
response.setContentType("text/plain;charset=UTF-8");
// 回傳 XML
response.setContentType("text/xml;charset=UTF-8");
escape() 或 encodeURI() 編碼,伺服器端再用 URLDecoder.decode("", "UTF-8") 解碼。一句話:前後端的資料交換全程統一用 UTF-8,就不會有亂碼。