用 $.ajax 傳遞中文參數時出現亂碼,問題往往不在你的字串,而在 jQuery 預設送出的 content type。
jQuery 預設的 contentType 是 application/x-www-form-urlencoded,在未明確指定字元集的情況下,瀏覽器會依 ISO-8859-1(Latin-1)編碼。Latin-1 只涵蓋西歐語言所需的附加字元,中文自然無法正確表示。這不是 jQuery 刻意為之,而是它早期沒有把國際化納入考量。
最直接的方式是告訴 jQuery 你要用 UTF-8。可以逐次呼叫時指定,也可以改動 jQuery 的原始設定(以 jquery-1.4.4.min.js 為例):
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 }
}
加上 charset=UTF-8 之後,不必再改 web.config、也不必在頁面調整編碼,中文就跟英文一樣直接傳,也不需要 escape() 之後再到伺服器解碼。
function confirmcommit() {
var wlCompany = $("#wlCompany").val(); // 含中文
var wlId = $("#wlId").val();
var proposer = $("#proposer").val();
if (!confirm("確認要換貨嗎")) return;
$.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);
if (msg == '換貨成功') {
document.location = "${pageContext.request.contextPath}"
+ "/orderItem/queryProduceItem.do?orderBusType=" + ${orderBusType};
}
}
});
}
前端送 UTF-8,後端就得用 UTF-8 讀。以 Struts 的 Action 為例:
public ActionForward confrimExchangeGoods(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
response.setCharacterEncoding("UTF-8"); // 這裡要設置一下
String wlCompany = request.getParameter("wlCompany");
String wlId = request.getParameter("wlId");
String proposer = request.getParameter("proposer");
// ...
}
編碼這條鏈路(頁面 → 請求 → 容器 → 應用 → 資料庫)只要有一環不對齊就會亂碼,逐段確認比盲猜有效得多。