jQuery AJAX GET 請求傳遞中文參數,伺服端接收到亂碼(如 %E6%B5%8B%E8%AF%95 未正確解碼)。
$.ajax({
type: 'POST',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
url: 'handler.ashx?Method=Update&folderName=' + encodeURI(encodeURI(folderName)),
success: function(msg){ alert(msg); }
});
encodeURI 將中文轉為 UTF-8 百分號編碼。encodeURI 將百分號 % 再編碼為 %25,防止瀏覽器/伺服器預設以其他編碼(如 GB2312)解碼第一層。// C# (ASP.NET)
string folderName = Request["folderName"]; // 第一層解碼(自動)
string folderName2 = HttpUtility.UrlDecode(folderName); // 第二層手動解碼
// 此時 folderName2 為正確中文
Request 自動解碼一次,若前端預先編碼一次,則需手動再解碼一次。$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({folderName: folderName}),
...
});
<meta charset="utf-8">Content-Type: text/html; charset=utf-8<globalization requestEncoding="utf-8" responseEncoding="utf-8" />& = 等保留字元),比 encodeURI 更安全。// 前端
var params = { folderName: folderName, custId: custId };
$.post('handler.ashx', params, function(res){ ... }); // jQuery 內建 encodeURIComponent
// 後端 (ASP.NET Core)
[HttpPost]
public IActionResult Update([FromForm] string folderName, [FromForm] int custId) {
// 模型綁定自動處理 UTF-8 解碼
return Ok(service.Update(folderName, custId));
}