xhr timeout在ie11中给出无效状态错误

时间:2017-04-12 05:46:05

标签: javascript jquery ajax xmlhttprequest

我试图在XMLHttpRequest中设置超时但显示invalid state error,这是代码

function get(url, options) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();

    // headers
    if (options && options.headers) {
      for (let header in options.headers) {
        if (options.headers.hasOwnProperty(header)) {
          xhr.setRequestHeader(header, options.headers[header]);
        }
      }
    }

    xhr.open('GET', url);
    // FIXME: Why is IE11 failing on "xhr.timeout?
    // xhr.timeout = 10000;

    xhr.onload = function () {
      if (this.status >= 200 && this.status < 300) {
        try {
          const data = JSON.parse(xhr.responseText);
          resolve(data);
        } catch (ex) {
          reject({
            status: this.status,
            statusText: xhr.statusText
          });
        }
      } else {
        reject({
          status: this.status,
          statusText: xhr.statusText
        });
      }
    };

    xhr.ontimeout = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };

    xhr.onerror = function () {
      reject({
        status: this.status,
        statusText: xhr.statusText
      });
    };

    xhr.send();
  });
}

export default { get };

enter image description here

我查看了以下链接link1 link2 link3,并在xhr.timeoutxhr.open之间明确保留了xhr.send

我甚至试过这个

xhr.onreadystatechange = function () {
  if(xhr.readyState == 1 ) {
    xhr.timeout = 5000;
  }
};

但没有运气

2 个答案:

答案 0 :(得分:2)

(++)方法之后添加xhr.timeout

答案 1 :(得分:1)

仅当在异步模式下调用xhr.timeout时,才应设置xhr.open(),否则MSIE将引发异常INVALID_STATE_ERR

示例: xhr.open(“ POST”,url,true);

ps。奇怪的是,我在FF和Chrome中看不到此问题。