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.org.cn/";
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 |
浏览器兼容性
加载中…