jQuery AJAX 提交含中文參數,後台 Action 接收到亂碼。
// 前端
data: { id: 1, type: encodeURI(encodeURI('商品')) }
// 後台
String type = request.getParameter("type");
type = URLDecoder.decode(type, "UTF-8");
缺點:雙重編碼易出錯,後台需手動解碼。
$.ajax({
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: { id: 1, type: '商品' },
...
});
優點:jQuery 內部已做 encodeURIComponent,後台無需解碼,直接獲取正確字符串。
charset=UTF-8 後,Tomcat 按 UTF-8 解碼請求體,完美支持中文。Content-Type。在 web.xml 配置 CharacterEncodingFilter(Spring 提供),強制請求/響應編碼為 UTF-8,徹底解決全站編碼問題。