現在的專案幾乎都以 UTF-8 作為標準編碼。但當你用 Ajax 去抓一個 GB2312 編碼的伺服器端頁面時,中文一定會亂——因為 XMLHttpRequest 預設以 UTF-8 來解讀回應內容,而實際收到的位元組是 GB2312。編碼不對,解出來的當然是亂碼。
很多人會想用 prototype.js 解決,但它的 Ajax 模組回傳的 responseBody 是 undefined,拿不到原始位元組。後來才發現:XMLHttpRequest 的 responseBody 屬性其實保存了未經解碼的原始資料——這是 IE 特有的擴充,正好是我們需要的。於是自己動手寫了一個輕量級的 Ajax 框架。
myAjaxCall({
url : 'xxxxx.jsp', // 目標頁面位址
params : URLEncoding('prm1=參數1&prm2=參數2'), // 參數串
method : 'POST', // POST or GET
callBack : retValue, // 回呼函式名稱
isBody : true // 回傳 responseBody(原始位元組)
// isXml : false, // 是否以 XML 格式回傳
// errorReport : false, // 發生錯誤時是否彈出提示
// attachs : {} // 傳給回呼函式的附加參數
});
function retValue(res, att){
var strRet = bytes2BSTR(res); // 把原始位元組轉成正確編碼的字串
alert(strRet);
}
關鍵在兩個函式:URLEncoding 負責把送出的參數編碼,bytes2BSTR 負責把收到的位元組解碼。兩者原先是 VBScript 寫的,在這裡以 ASP 標籤的形式與頁面放在一起:
<%
Function URLEncoding(vstrIn)
strReturn = ""
For i = 1 To Len(vstrIn)
ThisChr = Mid(vStrIn, i, 1)
If Abs(Asc(ThisChr)) < &HFF Then
strReturn = strReturn & ThisChr
Else
innerCode = Asc(ThisChr)
If innerCode < 0 Then innerCode = innerCode + &H10000
Hight8 = (innerCode And &HFF00) \ &HFF
Low8 = innerCode And &HFF
strReturn = strReturn & "%" & Hex(Hight8) & "%" & Hex(Low8)
End If
Next
URLEncoding = strReturn
End Function
Function bytes2BSTR(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn, i, 1))
If ThisCharCode < &H80 Then
strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn, i + 1, 1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
bytes2BSTR = strReturn
End Function
%>
bytes2BSTR 的原理很直白:逐位元組讀取,若最高位為 0(ASCII 範圍)就直接轉字元;否則代表這是一個雙位元組的中文字,把兩 byte 合成一個整數再轉字元,並把索引多推一格。
框架分成兩層:myAjaxCall() 負責合併設定與處理 no-cache,myAjaxCore() 則是實際的請求核心。
var myAjaxConfig = {
"url": "", "params": "", "method": "GET",
"callBack": function(){},
"isXml": false, "isBody": false, "isCache": false,
"errorReport": true, "statePoll": null,
"postData": null, "attachs": {}
};
function myAjaxCall(requestJson){
if (requestJson && typeof requestJson == "object"){
if (requestJson.url) myAjaxConfig.url = requestJson.url;
if (requestJson.params) myAjaxConfig.params = requestJson.params;
if (requestJson.method) myAjaxConfig.method = requestJson.method;
if (requestJson.callBack) myAjaxConfig.callBack = requestJson.callBack;
if (requestJson.isXml) myAjaxConfig.isXml = requestJson.isXml;
if (requestJson.isBody) myAjaxConfig.isBody = requestJson.isBody;
if (requestJson.isCache) myAjaxConfig.isCache = requestJson.isCache;
if (requestJson.statePoll) myAjaxConfig.statePoll = requestJson.statePoll;
if (requestJson.attachs) myAjaxConfig.attachs = requestJson.attachs;
}
if (!myAjaxConfig.isCache){
var nocache = new Date().getTime();
myAjaxConfig.url += (myAjaxConfig.url.indexOf(">") > 0 ? "&" : "?") + "nocache=" + nocache;
}
var newCall = new myAjaxCore();
newCall.init();
}
核心部分負責三件事:建立跨瀏覽器的 XHR 物件(IE 需依序嘗試 MSXML2.XMLHTTP.6.0 到 Microsoft.XMLHTTP)、依 method 決定要不要送 body、以及在 onreadystatechange 中依 isXml / isBody 選擇回傳 responseXML、responseBody 或 responseText。同時它也包含了狀態輪詢(statePoll)、HTTP 錯誤碼判斷、以及 abort / state / status / destory 等輔助方法,並附上一段以 userAgent 判斷瀏覽器的 browser 物件。
好消息是,這整類問題已經有標準答案,而且簡短得多:
// 方法一:用 responseType 直接取原始位元組,再自行解碼
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer';
xhr.onload = function(){
var bytes = new Uint8Array(xhr.response);
var text = new TextDecoder('gb2312').decode(bytes); // 指定來源編碼
console.log(text);
};
xhr.send();
TextDecoder 支援 WHATWG 編碼標準中的所有編碼,gb2312、gbk、big5 都在列,一行就解決了過去要寫幾十行 VBScript 的事。
// 方法二:直接覆寫 MIME 型別(適用於 jQuery 等舊寫法)
xhr.overrideMimeType('text/plain; charset=gb2312');
而更正本清源的做法是:把伺服器端也改成 UTF-8。設定資料庫連線編碼、頁面的 Content-Type 標頭與 HTML 的 <meta charset> 全部一致,這個問題就不復存在。跨編碼的轉換永遠是風險點,能消除就該消除。
這篇文章保留下來的價值,是它清楚說明了「亂碼 = 位元組被以錯誤的編碼解讀」這個本質,以及「拿原始位元組自己解碼」這個通用思路——即使今天用 TextDecoder 一行取代,理解仍然重要。