readyState 五個階段
| 值 | 常量 | 含義 | 典型回調 |
| 0 | UNSENT | 對象創建,open() 未調用 | onCreate (Prototype) |
| 1 | OPENED | open() 已調用,send() 未調用 | - |
| 2 | HEADERS_RECEIVED | 響應頭已接收 | onLoading (部分庫) |
| 3 | LOADING | 響應體下載中 | onLoading / onProgress |
| 4 | DONE | 請求完成 (成功/失敗/中止) | onComplete / onSuccess / onFailure |
常見庫的回調映射 (以 Prototype.js 為例)
Ajax.Request(url, {
onCreate: function() { ... }, // readyState 0→1
onLoading: function() { ... }, // readyState 3
onLoaded: function() { ... }, // readyState 4 但未檢查 status
onComplete: function(transport) { // readyState 4
if (transport.status == 200) onSuccess...
else onFailure...
}
});
現代 Fetch API 對比
fetch(url)
.then(response => response.json()) // 響應頭已拿到,體流式讀取
.then(data => console.log(data))
.catch(err => console.error(err));
// 無 readyState 概念,基於 Promise 鏈處理各階段
調試技巧
xhr.onreadystatechange = function() {
console.log('readyState:', xhr.readyState, 'status:', xhr.status);
if (xhr.readyState === 4) {
console.log('Response:', xhr.responseText);
}
};