DIV CSS 佈局教程網

jQuery ajax 傳遞中文亂碼:成因分析與四種解決方案
編輯:JQuery特效代碼     

用 jQuery 的 ajax 提交含中文的數據,後台收到的卻是亂碼——這是早期 Java Web 開發中最常見的坑之一。下面把成因和解法系統梳理一遍。

問題現場

$.ajax({
    dataType: 'json',
    type: 'POST',
    url: 'https://localhost/test/test.do',
    data: { id: 1, type: '商品' },
    success: function(data) { }
});

提交後後台 action 取到的 type 是亂碼。

方案一:前端兩次 encodeURI + 後台 decode

注意一定是兩次編碼:

data: { id: 1, type: encodeURI(encodeURI('商品')) }

後台 action 中再解碼:

String type = request.getParameter("type");
type = URLDecoder.decode(type, "UTF-8");

方案二:設置 contentType 並指定 charset

contentType: "application/x-www-form-urlencoded; charset=UTF-8"

關鍵在於 charset=UTF-8 這一段。其他 JS 框架或直接用 XHR 也是同樣思路——設置 header 中的 contentType 即可。如果少了 charset,是不會生效的;jQuery 默認的 contentType 裡並沒有它。

系統化測試結果

測試環境:jQuery 1.3.2、Tomcat 5.5.17。

GET 方式

服務端:

String name = new String(request.getParameter("name").getBytes("iso8859-1"), "utf-8");

客戶端與結果對照:

$.ajax({ url: "2.jsp", type: "get", data: { name: "中文" }, success: ... });
// 結果:正確顯示

$.ajax({ url: "2.jsp", type: "get", data: "name=中文", success: ... });
// 結果:亂碼

$.get("2.jsp", { name: "中文" }, function(response) { ... });
// 結果:正確顯示

$.get("2.jsp", "name=中文", function(response) { ... });
// 結果:亂碼

規律很清晰:傳對象時 jQuery 會自動 encodeURI,傳字符串時不會。這就是差異的根源。

POST 方式

服務端:

request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");

客戶端四種寫法全部正確顯示:

$.ajax({ url: "3.jsp", type: "post", data: "method=testAjaxPost&name=中文", success: ... });
$.ajax({ url: "3.jsp", type: "post", data: { name: "中文" }, success: ... });
$.post("3.jsp", { name: "中文" }, function(response) { ... });
$.post("3.jsp", "name=中文", function(response) { ... });

POST 之所以沒問題,是因為瀏覽器提交表單時默認按 UTF-8 編碼表單數據,只要服務端用 setCharacterEncoding("UTF-8") 對齊即可。

方案三:用 Filter 統一處理編碼

public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    if (req.getHeader("X-Requested-With") != null &&
        req.getHeader("X-Requested-With").equalsIgnoreCase("XMLHttpRequest")) {
        request.setCharacterEncoding("utf-8");
    } else {
        request.setCharacterEncoding("gbk");
    }
    chain.doFilter(request, response);
}

原理:jQuery 使用 ajax 時會在 header 中加入 X-Requested-With: XMLHttpRequest。Filter 中判斷到這個標記,就把編碼設為 UTF-8,否則沿用 GBK。這樣既能解決 ajax POST 的中文亂碼,又不必在每個 action 裡重複寫 setCharacterEncoding,也不影響頁面表單的正常提交。

方案四:自定義 header 標記(兼容 Prototype 風格)

為了和 prototype.js 的處理方式保持一致,可以自定義一個 RequestType 頭:

$.ajax({
    url: "3.jsp",
    type: "post",
    data: { name: "中文" },
    beforeSend: function(XMLHttpRequest) {
        XMLHttpRequest.setRequestHeader("RequestType", "ajax");
    },
    success: function(data, textStatus) { alert(data); },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("錯誤:" + textStatus);
    },
    complete: function(XMLHttpRequest, textStatus) {
        alert("完成:" + textStatus);
    }
});

對應的 Filter:

public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    if (req.getHeader("RequestType") != null &&
        req.getHeader("RequestType").equalsIgnoreCase("ajax")) {
        request.setCharacterEncoding("utf-8");
    } else {
        request.setCharacterEncoding("gbk");
    }
    chain.doFilter(request, response);
}

實踐建議

  • 能 POST 就不要用 GET 提交中文。GET 的編碼鏈路更長(瀏覽器 → URL → 服務器容器解碼),環節越多越容易出問題。
  • 統一全站編碼為 UTF-8 是根本解法:頁面 meta、服務器 connector、Filter、數據庫連接串全部對齊,亂碼問題會自然消失。
  • GET 傳對象而非字符串,讓 jQuery 自動完成 URL 編碼,是最省事的做法。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved