ASP 頁面輸出動態內容時,常面臨兩大問題:編碼不一致導致亂碼 (如郵件發送、AJAX 回傳)、未轉義導致 XSS。本文提供兩個通用函數:HtmlEntities (HTML 實體化) 與 JSUnicode (JS Unicode 轉義),從根源解決。
<%
Function HtmlEntities(str)
Dim i, char, code, result
result = ""
If IsNull(str) Then HtmlEntities = "" : Exit Function
For i = 1 To Len(str)
char = Mid(str, i, 1)
code = AscW(char)
' 非 ASCII 可打印字符 (0-31 控制字符, 127 DEL, >127 多字節) 轉實體
If code > 127 Or code < 32 Or code = 127 Then
' 使用十進制數字實體:代碼;
result = result & "" & CLng("&H" & Hex(code)) & ";"
Else
result = result & char
End If
Next
HtmlEntities = result
End Function
%>
<%
Dim test : test = "測試 & 特殊字符"
Response.Write HtmlEntities(test)
' 輸出:测试 <script>alert(1)</script> & 特殊字告
' 瀏覽器渲染為:測試 & 特殊字符 (安全、無亂碼)
%>
<%
Function JSUnicode(str1)
Dim i, char, hexStr, result
result = ""
If IsNull(str1) Then JSUnicode = "" : Exit Function
For i = 1 To Len(str1)
char = Mid(str1, i, 1)
hexStr = Hex(AscW(char))
' 補齊 4 位十六進制:\uXXXX
If Len(hexStr) < 4 Then hexStr = Right("0000" & hexStr, 4)
result = result & "\u" & hexStr
Next
JSUnicode = result
End Function
%>
Response.Write "callback(" & JSUnicode(jsonStr) & ");"var msg = "\u6d4b\u8bd5"; 任意編碼頁面均可正確解析<script>
var msg = "<%=JSUnicode("中文測試'引號<script>")%>";
alert(msg); // 正確彈出:中文測試'引號