ASP 預設 CodePage 為 936 (GB2312/GBK),若網頁宣告 UTF-8 卻未正確設定伺服器端編碼,從 Access 讀出的中文會變亂碼。解決核心在於**伺服器端腳本編碼、HTTP 回應標頭、檔案儲存編碼**三者一致。
<% @CodePage=65001 %> (須在檔案最第一行)<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> (或 Response.Charset="UTF-8" / Response.ContentType="text/html;charset=UTF-8")<% Session.CodePage = 65001 %> (確保 Session 變數編碼一致)<%@ Language=VBScript CodePage=65001 %>
<%
Session.CodePage = 65001
Response.Charset = "UTF-8"
Response.ContentType = "text/html;charset=UTF-8"
%>
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>UTF-8 ASP 範例</title>
</head><body>
<%
' 測試資料庫讀取
Dim conn, rs
Set conn = Server.CreateObject("ADODB.Connection")
conn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("db.mdb")
Set rs = conn.Execute("SELECT TOP 1 title FROM articles")
If Not rs.EOF Then
Response.Write "資料庫標題:" & rs("title") & "
"
End If
rs.Close: Set rs = Nothing
conn.Close: Set conn = Nothing
%>
</body></html>
@CodePage 或 Session.CodePage 解讀位元組<meta> 解碼顯示| 誤區 | 正確做法 |
|---|---|
只加 <meta charset="UTF-8"> | 伺服器端仍以 936 送出位元組,瀏覽器以 UTF-8 解碼 → 亂碼 |
只加 @CodePage=65001 但檔案存為 ANSI | 原始碼中文常數已被編成 ANSI 位元組,腳本引擎以 UTF-8 讀取 → 亂碼 |
| 以為資料庫要轉 UTF-8 | Access 無需轉碼,關鍵在 Provider 轉碼與 ASP CodePage 一致 |
| 程式有語法錯誤導致「首次正常、重新整理亂碼」 | 錯誤頁面可能忽略 CodePage 設定,修正所有語法錯誤 |
Response.Write "中文測試",確認瀏覽器顯示正常Content-Type 標頭是否含 charset=UTF-8E4 B8 AD E6 96 87)Function ReadUTF8(filePath)
Dim stream : Set stream = CreateObject("ADODB.Stream")
stream.Type = 2 : stream.Charset = "UTF-8" : stream.Open
stream.LoadFromFile filePath
ReadUTF8 = stream.ReadText
stream.Close
End Function
Function WriteUTF8(filePath, content)
Dim stream : Set stream = CreateObject("ADODB.Stream")
stream.Type = 2 : stream.Charset = "UTF-8" : stream.Open
stream.WriteText content
stream.SaveToFile filePath, 2 ' adSaveCreateOverWrite
stream.Close
End Function
ASP + UTF-8 三要素:**@CodePage=65001、Response.Charset=UTF-8、檔案存為 UTF-8 無 BOM**,加上 Session.CodePage=65001 保障 Session 資料。只要三者一致,Access 中文資料即可正常讀寫,徹底告別亂碼。