$.ajax 指定 dataType 為 json 時,若回應不是合法 JSON,或 Content-Type 不相符,jQuery 會進入 error 而非 success。跨域未設定 Access-Control-Allow-Origin 也可能造成同樣現象。
可先在 error 中輸出 XMLHttpRequest.responseText、status、readyState 與 textStatus,確認是解析錯誤、跨域問題或伺服器回傳格式異常。
error: function (xhr, textStatus) {
console.log(xhr.responseText);
console.log(xhr.status);
console.log(textStatus);
}
鍵名與字串值都應使用雙引號,數字與布林值不需加引號。若後端輸出 HTML、XML 宣告或前後空白字元,也可能導致解析失敗。