怎样监听xhr.readyState值的变化

可以使用 xhr.onreadystatechange 属性指向的函数去监听 xhr.readyState 值的变化. 示例如下: 

var xhr = new XMLHttpRequest();
xhr.open( 'GET', 'http://example.com' , true );
xhr.onreadystatechange = function () {
  if (xhr.readyState !== 4 || xhr.status !== 200) {
    return;
  }
  console.log(xhr.responseText);
};
xhr.send();

 

注意: 除了xhr的正常请求过程会改变 xhr.readyState 值以外, 类似xhr.abort()这种会终止请求的方法也会改变xhr.readyState的值.

 

posted on 2019-09-20 01:59  aisowe  阅读(691)  评论(0编辑  收藏  举报

导航