明明伺服器回傳 200 OK,卻進入 error 回呼,textStatus 顯示 parsererror。
預設 async: true,若後續程式碼依賴 AJAX 回傳資料,卻在請求完成前執行,會造成邏輯錯誤。設定 async: false 強制同步等待:
$.ajax({
type: 'POST',
async: false, // 同步請求(注意:會阻塞 UI,慎用)
url: urllink,
data: data,
dataType: 'html',
success: function(msg) { alert(msg); },
error: function(xhr, status, err) {
console.log(xhr.status, xhr.readyState, status, err);
}
});
警告:async: false已被標準棄用,會凍結瀏覽器主執行緒。現代專案請改用Promise/async-await或回呼/事件機制處理非同步流程。
data: "{}" 未正確傳遞空物件若不需傳參數,必須傳 data: "{}" 或 data: {},否則 jQuery 可能送出空字串,導致伺服器回傳非預期格式(如 XML 錯誤頁),引發 parsererror。
// ❌ 易出錯
$.ajax({ dataType: 'json', data: '', ... });
// ✅ 正確
$.ajax({ dataType: 'json', data: {}, ... }); // 或 data: '{}'
error: function(xhr, textStatus, errorThrown) {
console.group('AJAX Error');
console.log('status:', xhr.status); // HTTP 狀態碼
console.log('readyState:', xhr.readyState); // 0-4
console.log('textStatus:', textStatus); // timeout, error, abort, parsererror
console.log('errorThrown:', errorThrown); // 例外物件或字串
console.log('responseText:', xhr.responseText); // 原始回應
console.groupEnd();
}
textStatus 對照| 值 | 含義 |
|---|---|
| timeout | 請求逾時 |
| error | HTTP 錯誤 (4xx, 5xx) |
| abort | 請求被中止 |
| parsererror | 資料解析失敗 (JSON/XML 格式錯誤) |
parsererror,檢查 dataType 與實際回傳是否匹配。$.ajax().done(fn).fail(fn) 鏈式寫法或 await $.ajax(...)(需 Promise 封裝)。{ success: false, msg: '...' },前端統一在 success 判斷 data.success,避免進入 error。