jQuery $.ajax 預設 contentType: "application/x-www-form-urlencoded; charset=UTF-8",但早期版本未明確指定 charset,導致伺服器以 ISO-8859-1 解碼,中文產生亂碼。
// jquery-x.x.x.js 中找到 ajaxSettings
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // 加上 charset
processData: true,
async: true,
...
}
缺點: 升級 jQuery 時需重複修改,維護困難。
$.ajaxSetup({
contentType: "application/x-www-form-urlencoded; charset=UTF-8"
});
在引入 jQuery 後、第一次 AJAX 前呼叫一次即可。
$.ajax({
type: "POST",
url: "xxx.do",
data: { wlCompany: "中文公司名", wlId: "123" }, // 使用物件,jQuery 自動編碼
dataType: "json",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function(res) { ... }
});
關鍵: data 使用**物件**而非字串拼接,jQuery 會自動 encodeURIComponent 處理中文。
// Java Servlet
request.setCharacterEncoding("UTF-8"); // 必須在 getParameter() 前呼叫
String wlCompany = request.getParameter("wlCompany");
// Spring MVC
@RequestMapping(value="/xxx", produces="application/json;charset=UTF-8")
@ResponseBody
public Result xxx(@RequestParam String wlCompany) { ... }
// PHP
header('Content-Type: application/json; charset=utf-8');
$wlCompany = $_POST['wlCompany']; // 需確保 PHP 內部編碼為 UTF-8
| 層級 | 設定 |
|---|---|
| HTML 頁面 | <meta charset="UTF-8"> |
| JS 檔案 | 儲存為 UTF-8 無 BOM |
| AJAX 請求 | contentType: "...; charset=UTF-8" + data 用物件 |
| 伺服器 | request.setCharacterEncoding("UTF-8") / 回應 header 含 charset |
| 資料庫 | 表/欄位/連線編碼 utf8mb4 |