首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

ASP.NET 與 jQuery 傳遞中文參數亂碼:編碼不一致與解決方案

     編輯:程式設計疑難解答

問題場景

  1. 後端 C# 拼接 URL:href='showWebUpDown.aspx?firstTitle=新聞動態&secondTitle=" + xinwenList[i] + "&total=3'
  2. 前端頁面加載時,jQuery 解析 URL 參數 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;
}
  1. 初期正常,修改 CSS 後突然出現亂碼,其他頁面無異常。

核心原因:編碼鏈路不一致

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()

為什麼「改 CSS 後」突然壞了?

  • 保存文件時,編輯器(如 VS、Notepad++)可能將文件編碼從 UTF-8 無 BOM 轉為 UTF-8 with BOM、GB2312 或 ANSI。
  • 導致頁面實際編碼與聲明編碼(<meta charset="utf-8">)不符,瀏覽器按錯誤編碼發送請求/解析響應。

完整解決方案

後端 (C#) - 編碼生成 URL

// 引用 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>

前端 JS - 標準解碼

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;
}

驗證步驟

  1. 瀏覽器開發者工具 Network 面板,查看請求 URL 中 secondTitle 參數值是否為 %E6%96%B0%E8%81%9E... 格式(UTF-8 Percent-Encoding)。
  2. Console 執行 decodeURIComponent('%E6%96%B0%E8%81%9E') 驗證解碼邏輯。
  3. 確認所有 .aspx/.html/.js 文件均以 UTF-8 無 BOM 保存。

參考資源

URL 編碼/解碼詳細指南

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved