前幾天在寫一個「檢查使用者名稱是否已存在」的功能,前端用 $.post(),後端是一個 .ashx 泛型處理常式。邏輯看起來毫無問題,可回調裡的 alert(data) 遲遲不跳,單步跟蹤到最後才發現——問題出在後端吐回去的那串 JSON。
前端:
<script type="text/javascript">
function checkUser() {
var user = $('#<%=txtUser.ClientID %>').val();
$.post('checkUser.ashx', { Action: "Check", Name: user }, function (data) {
alert(data);
}, "json");
}
</script>
後端(checkUser.ashx):
public void ProcessRequest(HttpContext context) {
context.Response.ContentType = "application/json";
string action = context.Request["Action"];
string user = context.Request["Name"];
string result = "{result: 0}";
switch (action) {
case "Check":
if (us.isExists(user)) {
result = "{result: 1}";
}
break;
}
context.Response.Write(result);
}
後端輸出的是 {result: 1},這種寫法在 JavaScript 物件字面量裡勉強算合法,但它不是合規的 JSON。jQuery 在 dataType 指定為 json 時會走嚴格解析,解析一失敗,success 自然永遠不會被呼叫。正確的寫法必須是:
{"result": 1}
另一個常見的變形是這種寫法:
$.ajax({
type: "post",
contentType: "application/json",
url: basePath + "pages/Tongji/disposeAgree.action?cepingitem=" + cepingitem + "&userrelation=" + userrelation,
dataType: "json",
success: function (result) { alert("操作成功"); },
error: function (response) { alert("error"); }
});
原因完全一樣:只要宣告了 dataType: "json",而後端回的不是合法 JSON 字串,那麼 success 就永遠不會觸發,流程只會落到 error。有兩條路可走——要麼讓後端吐出正確的 JSON,要麼把 dataType 改成 text 自行處理。
後端輸出時,字串值務必用半角雙引號,布林值則直接寫 true/false:
pw.write("{\"name\":\"zs\"}");
pw.write("{\"name\":" + true + "}");
而下面這種全形單引號的寫法一定是錯的:
pw.write("{‘name':‘zs'}"); // 全形引號,解析必失敗
遇到「回調不執行」時,與其盲猜,不如照這個順序檢查:先用瀏覽器開發者工具看 Network 面板裡實際的回應內容;確認 Content-Type 是否為 application/json;確認字串中的引號是半角;最後再回頭看 dataType 宣告與實際回應是否一致。九成的問題在這四步之內就會現形。