DIV CSS 佈局教程網

GB2312 轉 UTF-8 的 VBS 與 JS 交叉驗證實錄
編輯:關於JavaScript     

昨天看了 cocoon counter 的程式碼,發現裡面是用 VBScript 來轉碼的,於是花了一個上午研究,結果還是被搞得暈頭轉向。

VBS 的轉換函式

它的做法是用 Chr() 把十進位的 ANSI 字元碼轉成文字:

Function DeCodeAnsi(s)
  Dim i, sTmp, sResult, sTmp1
  sResult = ""
  For i = 1 To Len(s)
    If Mid(s, i, 1) = "%" Then
      sTmp = "&H" & Mid(s, i + 1, 2)
      If isNumeric(sTmp) Then
        If CInt(sTmp) = 0 Then
          i = i + 2
        ElseIf CInt(sTmp) > 0 And CInt(sTmp) < 128 Then
          sResult = sResult & Chr(sTmp)
          i = i + 2
        Else
          If Mid(s, i + 3, 1) = "%" Then
            sTmp1 = "&H" & Mid(s, i + 4, 2)
            If isNumeric(sTmp1) Then
              sResult = sResult & Chr(CInt(sTmp) * 16 * 16 + CInt(sTmp1))
              i = i + 5
            End If
          Else
            sResult = sResult & Chr(sTmp)
            i = i + 2
          End If
        End If
      Else
        sResult = sResult & Mid(s, i, 1)
      End If
    Else
      sResult = sResult & Mid(s, i, 1)
    End If
  Next
  DeCodeAnsi = sResult
End Function

也就是說,文字本身應該是 Unicode,VBS 自動完成了 GB 到 UTF 的轉換。於是設計了一組測試來驗證這件事。

測試程式碼

<SCRIPT RUNAT=SERVER LANGUAGE=javascript>
Response.write("<br/>strx = chr(54992):");
Response.write(strx);
Response.write("<br/>strx.charCodeAt(0):");
Response.write(strx.charCodeAt(0));
Response.write("<br/>\"中\".charCodeAt(0):");
Response.write("中".charCodeAt(0));
Response.write("<br/>escape(strx):");
Response.write(escape(strx));
Response.write("<br/>encodeURI(strx):");
Response.write(encodeURI(strx));
Response.write("<br/>String.fromCharCode(20013):");
Response.write(String.fromCharCode(20013));
</SCRIPT>

交叉比對的結果

分別調整檔案儲存格式、codepage 與 charset,得到的結果如下。

檔案為 ANSI 格式、codepage=936、Response.Charset = "gb2312":
chr(54992) 顯示為「中」,charCodeAt(0) 為 20013,escape() 得 %u4E2D,encodeURI() 得 %E4%B8%AD,String.fromCharCode(20013) 回得到「中」。這是最理想的組合。

同樣 ANSI 檔、codepage=936,但 Response.Charset = "utf-8":
畫面上顯示成另一個字元,但 charCodeAt(0) 依然是 20013,escape() 依然是 %u4E2D。可見編碼在輸出層被改寫,字串在記憶體中的值並未改變。

codepage=65001:
若 charset 設為 gb2312,chr(54992) 會顯示成「涓」,而且 "".charCodeAt(0) 直接回傳 -1.#IND;若 charset 設為 utf-8,則 charCodeAt(0) 變成 14180,escape() 變成 %u3764——這已經是另一個字元了。

檔案為 UTF-8 格式、codepage=65001:
charset 設為 gb2312 時顯示為「涓」但 charCodeAt(0) 為 20013;設為 utf-8 時 String.fromCharCode(20013) 又能正確還原。

從這些數字能學到什麼

結論其實很單純:charCodeAt 回傳的是字串在記憶體中的 Unicode 碼位,它不會因為 Response.Charset 改變而改變;改變的只是輸出到網路上時的字元編碼。真正會讓你「字變成別的字」的,是檔案本身的儲存格式與 codepage 不相符——這時瀏覽器用錯的碼頁去解位元組,畫面上就會出現看似相關卻完全不同的漢字。

所以排查這類問題時,請先把三件事對齊:檔案實際的儲存編碼、伺服器回應的 Content-Type; charset=、以及 HTML 中的 meta charset。這三者只要有一個不合,就會出現「編碼沒錯但畫面亂掉」的經典症狀。今天所有專案都應該統一使用 UTF-8,這個問題也就不復存在。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved