jQuery 預設的 contentType 是 application/x-www-form-urlencoded,在未指定字元集的情況下,會使用 ISO-8859-1。這才是中文傳遞時出現亂碼的根源。
ISO-8859-1(通常稱為 Latin-1)包含了書寫西歐語言所需的附加字元,卻完全不含中文。jQuery 的 Ajax 在設計時沒有把國際化納入考量,沿用了這個歐洲字元集,於是中文就壞掉了。而 UTF-8 能涵蓋中文,正是解法所在。
思路很直接:顯式宣告 contentType 使用 UTF-8 字元集,GB2312 中文傳遞的問題即可解決。
找到使用的 jQuery 檔(範例為 jquery-1.4.4.min.js),在 ajaxSettings 中補上 charset:
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
processData: true,
async: true,
xhr: function () { return new E.XMLHttpRequest }
}
這樣就不必改 web.config、也不必在頁面調編碼或用 escape() 編碼再於伺服器解碼——英文怎麼傳,中文就怎麼傳。
不過要提醒:直接改動函式庫原始碼並不推薦。每次升版都要重改一次,而且壓縮過的檔案幾乎無法安全維護。更好的做法是設定全域的 $.ajaxSetup():
$.ajaxSetup({
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
});
效果相同,卻完全不必碰原始碼。
function confirmcommit() {
var wlCompany = $("#wlCompany").val(); // 這裡含有中文
var wlId = $("#wlId").val();
var proposer = $("#proposer").val();
if (confirm("確認要換貨嗎")) {
$.ajax({
type: 'POST',
url: '${pageContext.request.contextPath}/returnGoods/confrimExchangeGoods.do',
data: { wlCompany: wlCompany, wlId: wlId, proposer: proposer },
dataType: 'text',
error: function () { alert("JQuery AJAX Error!"); },
success: function (msg) { alert(msg); }
});
}
}
public ActionForward confrimExchangeGoods(ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
log.info("確認換貨 confrimExchangeGoods start...............");
response.setCharacterEncoding("UTF-8"); // 這裡一定要設定
String wlCompany = request.getParameter("wlCompany");
String wlId = request.getParameter("wlId");
String proposer = request.getParameter("proposer");
// ...
}
值得強調的是:前端宣告 UTF-8 只解決了「送出去」的一半。若後端沒有相應地以 UTF-8 解讀請求、編碼回應,亂碼照樣會出現。一次到位的檢查清單是:
contentType 標明 UTF-8,參數用 encodeURIComponent() 或直接傳物件。request.setCharacterEncoding("UTF-8")(在讀取任何參數之前呼叫),或在 web.xml 中掛上編碼 filter。response.setCharacterEncoding("UTF-8") 與 response.setContentType("text/html;charset=UTF-8")。只要這四個環節一致,中文就不會再亂碼。