【问题标题】:xhr timeout gives invalid state error in ie11xhr 超时在 ie11 中给出无效状态错误
【发布时间】:2017-04-12 05:46:04
【问题描述】:

我试图在 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 };

我查看了以下链接 link1 link2 link3 并特别将 xhr.timeout 保留在 xhr.openxhr.send 之间

我什至试过这个

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

但运气不好

【问题讨论】:

  • 关于您的 FIXME 评论:@Mozila 是关于它的注释。

标签: javascript jquery ajax xmlhttprequest


【解决方案1】:

xhr.open 方法之后添加xhr.timeout

【讨论】:

【解决方案2】:

只有在异步模式下调用xhr.open()时才应该设置xhr.timeout,否则MSIE会引发异常INVALID_STATE_ERR

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

ps。奇怪的是,我在 FF 和 Chrome 中没有看到这个问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-30
    • 2023-03-18
    • 1970-01-01
    • 2018-06-24
    • 1970-01-01
    相关资源
    最近更新 更多