原文地址:http://blog.csdn.net/hongweigg/article/details/6756278
1. jQuery AJAX 請求,後台收到為亂碼
可以顯式設定contentType的編碼為utf-8, 後台一般都能正常解碼例如:
[javascript]
view plaincopyprint?
- contentType: "application/x-www-form-urlencoded; charset=utf-8",
contentType: "application/x-www-form-urlencoded; charset=utf-8",
[javascript]
view plaincopyprint?
- jQuery(form).ajaxSubmit({
- url: "doLogin?user=a",
- type: "post",
- dataType: "json",
- contentType: "application/x-www-form-urlencoded; charset=utf-8",
- success: showLoginResponse
- });
jQuery(form).ajaxSubmit({url: "doLogin?user=a",type: "post",dataType: "json",contentType: "application/x-www-form-urlencoded; charset=utf-8",success: showLoginResponse});
如果不加contentType: "application/x-www-form-urlencoded; charset=UTF-8", 而使用escape(),則會出現
post 主體包含的位元組比內容長度指定的位元組要少
的錯誤.
2. jQuery AJAX 返回亂碼
你是否發現無論你怎麼設定編碼, 用戶端收到的資料總是亂碼呢, 請看下面的例子,你發現有什麼問題嗎?
[java]
view plaincopyprint?
- void saveTempKind(HttpServletRequest req, HttpServletResponse resp)
- throws ServletException, IOException {
- PrintWriter pw = resp.getWriter();
- resp.setContentType("text/text;charset=GBK");
- try {
- //DO PROCESS
- pw.write("成功");
- }catch(Exception e){
- pw.write("失敗");
- }
- }
void saveTempKind(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter pw = resp.getWriter(); resp.setContentType("text/text;charset=GBK"); try { //DO PROCESS pw.write("成功"); }catch(Exception e){ pw.write("失敗"); }}
問題在於resp.setContentType("text/text;charset=GBK");
語句應該在
[javascript]
view plaincopyprint?
- PrintWriter pw = resp.getWriter();
PrintWriter pw = resp.getWriter();
之前,而不是之後。如果象上例這樣,無論你怎麼設定response的編碼,前端亂碼的問題都依然如故。 可能的原因是pw在獲得PriintWriter 之前,編碼就已經確定了。所以編碼的聲明應該在擷取PrintWriter對象之前。