XMLHttpRequest.onreadystatechange

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

只要 readyState 属性发生变化,就会调用相应的处理函数。这个回调函数会被用户线程所调用。XMLHttpRequest.onreadystatechange 会在 XMLHttpRequestreadyState 属性发生改变时触发 readystatechange 事件的时候被调用。

警告: 这个方法不该用于同步的 requests 对象,并且不能在内部 (C++) 代码中使用。

当一个 XMLHttpRequest 请求被 abort() 方法取消时,其对应的 readystatechange 事件不会被触发。

语法

在类似 addEventListener() 这样的方法中使用事件名称,或设置事件处理器属性。

js
addEventListener("readystatechange", (event) => {});

onreadystatechange = (event) => {};

取值

  • readyState 的值改变的时候,callback 函数会被调用。

示例

js
var xhr = new XMLHttpRequest(),
  method = "GET",
  url = "https://developer.mozilla.org/";

xhr.open(method, url, true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();

规范

Specification
XMLHttpRequest
# event-xhr-readystatechange
XMLHttpRequest
# handler-xhr-onreadystatechange

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
readystatechange event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support