XMLHttpRequest:readystatechange 事件
注意:此功能在 Web Workers 中可用,但 Service Workers 除外。
當 XMLHttpRequest 物件的 readyState 屬性發生變化時,就會觸發 readystatechange 事件。
警告:不應將其用於同步請求,且不得從原生程式碼中使用。
語法
在諸如 addEventListener() 之類的方法中使用事件名稱,或設定事件處理程式屬性。
js
addEventListener("readystatechange", (event) => { })
onreadystatechange = (event) => { }
事件型別
一個通用的 Event,沒有額外的屬性。
示例
js
const xhr = new XMLHttpRequest();
const method = "GET";
const url = "https://mdn.club.tw/";
xhr.open(method, url, true);
xhr.onreadystatechange = () => {
// In local files, status is 0 upon success in Mozilla Firefox
if (xhr.readyState === XMLHttpRequest.DONE) {
const status = xhr.status;
if (status === 0 || (status >= 200 && status < 400)) {
// The request has been completed successfully
console.log(xhr.responseText);
} else {
// Oh no! There has been an error with the request!
}
}
};
xhr.send();
規範
| 規範 |
|---|
| XMLHttpRequest # event-xhr-readystatechange |
| XMLHttpRequest # handler-xhr-onreadystatechange |
瀏覽器相容性
載入中…