本文記錄了一次實際的除錯過程,環境為:Visual Studio 2005(未安裝 SP1,只能建立網站而非 Web 應用程式)、jQuery 1.5.1。
<globalization requestEncoding="gb2312" responseEncoding="gb2312"/>
$(document).ready(function (){
$("#btnSend").click(function(){
$.ajax({
type: "POST",
url: "PrecisionAHandle.ashx",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {
"StudentId": $("#LblStudentId").attr("innerText"),
"StudentName": $("#LblStudentName").attr("innerText"),
"StudentAge": $("#txtStudentAge").attr("value")
},
success: function(html){
$("#TabContainer").html(html);
}
});
});
});
其中 StudentName 的值是中文。
string strStudentName = context.Request.Params["StudentName"];
關鍵:若不加上 contentType: "application/x-www-form-urlencoded; charset=UTF-8",context.Request.Params["StudentName"] 拿到的就是亂碼。
在 .ashx 中追蹤 context.Request.ContentEncoding 後可以推知:jQuery POST 過來的資料採 gb2312 編碼,而 context.Request 在接收時預設以 utf-8 解碼,兩者不符,於是產生亂碼。
現象一:在不加上那行 contentType 的情況下,若改以下列方式讀取,字串卻能正確顯示:
StreamReader steamRd = new StreamReader(HttpContext.Current.Request.InputStream);
string strPostData = steamRd.ReadToEnd();
strPostData = HttpUtility.UrlDecode(strPostData, Encoding.GetEncoding("utf-8"));
原因在於這種做法繞過了 Request.Params 的自動解碼流程,改由自己指定 Encoding.GetEncoding("utf-8") 明確解碼,等於手動把編碼對齊回來了。
現象二:把 web.config 改為:
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
之後,無論是否加上那行 contentType,後端 .ashx 收到的參數仍然是亂碼。而且修改後網站的編譯與執行速度都明顯變慢。
把整條編碼鏈路攤開來看就清楚了。中文要正確往返,必須滿足:瀏覽器送出的位元組編碼、伺服器解讀時使用的編碼、以及 contentType 中宣告的字元集,三者一致。
现象一之所以可行,是因為程式碼手動指定了 utf-8 解碼,把 jQuery 實際送出的編碼正確還原。现象二之所以失敗,是因為只改了 web.config 的 requestEncoding,卻沒有同步處理頁面本身的輸出編碼——若頁面仍以 gb2312 輸出,或快取中的舊頁面未失效,送出的位元組與伺服器預期的 utf-8 依然對不上。至於速度變慢,則可能與此環境下未裝 SP1、以及編碼轉換所增加的負擔有關。
遇到這類問題,與其猜測,不如逐層驗證:
Content-Type,確認 charset 有沒有真的送出去。Encoding.UTF8.GetString(bytes) 觀察),判斷是「送來就錯了」還是「解讀時錯了」。globalization 設定、以及 AJAX 的 contentType 三者一致。參考文章:
https://www.poluoluo.com/article/26658.htm
https://www.poluoluo.com/article/26659.htm