href='showWebUpDown.aspx?firstTitle=新聞動態&secondTitle=" + xinwenList[i] + "&total=3'secondTitle:function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]); // 關鍵點
return null;
}
URL 傳遞中文涉及三個關鍵編碼環節,任一環節不匹配即產生亂碼:
| 環節 | 正確做法 | 常見錯誤 |
|---|---|---|
| 1. 後端生成 URL 時 | Server.UrlEncode(xinwenList[i]) 或 HttpUtility.UrlEncode (UTF-8) |
直接拼接字符串,依賴默認編碼(可能是 GB2312) |
| 2. 瀏覽器發起請求時 | 現代瀏覽器默認按頁面 <meta charset="utf-8"> 編碼發送 |
頁面無 charset 聲明,或 charset 與後端解碼不一致 |
| 3. 前端 JS 解碼時 | decodeURIComponent(r[2]) (HTML5 標準,對應 UTF-8) |
使用已棄用的 unescape() (不支持 UTF-8 多字節) 或 decodeURI() |
<meta charset="utf-8">)不符,瀏覽器按錯誤編碼發送請求/解析響應。// 引用 System.Web
string encodedTitle = HttpUtility.UrlEncode(xinwenList[i], System.Text.Encoding.UTF8);
string url = $"/showWebUpDown.aspx?firstTitle=新聞動態&secondTitle={encodedTitle}&total=3";
// 輸出到頁面: <a href='<%=url %>'>...
<%@ Page Language="C#" ContentType="text/html" ResponseEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" /> <!-- 必須放在 head 首位 -->
<title>...</title>
</head>
function getUrlParam(name) {
// 更健壯的正則,支持參數在末尾無 & 情況
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if (r != null)
return decodeURIComponent(r[2]); // 替換 unescape,支持 UTF-8
return null;
}
secondTitle 參數值是否為 %E6%96%B0%E8%81%9E... 格式(UTF-8 Percent-Encoding)。decodeURIComponent('%E6%96%B0%E8%81%9E') 驗證解碼邏輯。