Ajax 送中文到後端變成亂碼,是每個人都會遇到一次的問題。網路上大量討論指向同一個結論:Ajax 提交資料時使用 UTF-8 編碼,且無法改為其他格式。既然編碼端不能改,那就從「送出前先編碼」下手。
HTML 端:
<script type="text/javascript" language="javascript">
var xmlhttp;
function createXMLHttprequest() {
if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
}
function inData() {
var txtval = document.getElementById("txt").value;
createXMLHttprequest();
xmlhttp.open("GET", "request.ashx?val=" + txtval, true);
xmlhttp.onreadystatechange = getData;
xmlhttp.send(null);
}
function getData() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementById("showDT").innerHTML = xmlhttp.responseText;
}
}
}
</script>
後端 request.ashx:
<%@ WebHandler Language="C#" Class="request" %>
using System;
using System.Web;
public class request : IHttpHandler {
public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";
string tab = "來自伺服器的資訊:您好 " + context.Request.QueryString["val"].ToString()
+ " --by time:" + DateTime.Now.ToLongTimeString();
context.Response.Write(tab);
}
public bool IsReusable { get { return false; } }
}
Ajax 提交時固定使用 UTF-8,無法改成其他編碼。解法是找到 JavaScript 的 escape() 與 unescape() 這對函式——用 escape() 把要送出的中文編碼,會得到類似 %10%20 這種形式的字元序列,作用等同於 .NET 的 Server.UrlEncode() 與 Server.UrlDecode()。
把取到的表單值重新編碼一次即可:
var txtval = escape(document.getElementById("txt").value);
就這樣,中文正常顯示了。
亂碼的本質是「編碼不一致」:瀏覽器把中文按某種編碼送出去,伺服器卻用另一種編碼解讀,於是解出無意義的字。手工 escape() 只是把字元轉成 ASCII 安全的 %HH 形式,讓編碼這件事變得明確可控。
實務上更建議從源頭對齊:把頁面、資料庫、回應標頭全部統一成 UTF-8,例如 HTML 用 <meta charset="utf-8">、ASP.NET 在 web.config 裡設 globalization、PHP 輸出前加 header('Content-Type: text/html; charset=utf-8')。若仍要手工編碼,現代請用 encodeURIComponent() 取代 escape()——後者已被 deprecated,且對非 ASCII 字元的處理並不完整。