Ajax 送出的中文參數變成亂碼,多數情況是編碼不一致造成的。jQuery 預設的 contentType 是 application/x-www-form-urlencoded,未指定字元集時部分環境會以 ISO-8859-1 解讀,中文自然就壞了。
處理思路是在送出前對參數做編碼,並明確宣告 UTF-8。
smsubmitclick = function () {
$(document).ready(function () {
var name = $("#txt_name").val(); // 中文欄位
var type = $("#seltype option:selected").val();
var zjnum = $("#txt_num").val();
if (name == null || name == "") {
alert("請輸入您的真實姓名");
return false;
}
if (name.length > 20) {
alert("對不起,您的用戶名存在異常,請重新輸入");
$("#txt_name").focus().val("");
return false;
}
if (zjnum == null || zjnum == "") {
alert("請輸入證件號碼");
return false;
}
if (zjnum.length > 30) {
alert("對不起,您的證件存在異常,請重新輸入");
$("#txt_num").focus().val("");
return false;
}
$.ajax({
type: "get",
cache: false,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
url: "ajaxpage.aspx?t=smrz"
+ "&name=" + encodeURIComponent(name)
+ "&zjtype=" + encodeURIComponent(type)
+ "&zjnum=" + encodeURIComponent(zjnum),
dataType: "json",
success: function (data) {
alert(data.info);
}
});
});
};
中文亂碼可能出在四個環節,逐段確認最有效率:
<meta charset="utf-8"> 中宣告。encodeURIComponent() 對參數編碼,並在 contentType 中標明 UTF-8。原範例用的 escape() 對非 ASCII 字元的處理並不可靠,且已被廢棄,請改用 encodeURIComponent()。web.config 的 globalization 設定為 requestEncoding="utf-8" responseEncoding="utf-8"。Response.ContentEncoding = Encoding.UTF8。另外建議把中文參數改用 POST 並以物件形式傳遞,讓 jQuery 統一處理序列化與編碼,比手工拼網址安全得多:
$.ajax({
type: "post",
url: "ajaxpage.aspx?t=smrz",
data: { name: name, zjtype: type, zjnum: zjnum },
dataType: "json"
});
這樣寫不僅不必自己編碼,也避免了中文出現在網址列上被記錄或截斷的風險。最後提醒:身分證號這類敏感資料以 GET 傳送會留在伺服器與代理的查詢記錄中,實務上應一律走 POST 並配合 HTTPS。