为什么IE9(8)用try / catch区别对待XDR

问题描述 投票:1回答:1

所以我想在IE8,9中进行CORS,所以我必须使用XDomainRequest。所以我创建了:

function post(url, data) {
  var request = new XMLHttpRequest();
  try {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'text/plain');
  } catch (err) {
    if (err.message.indexOf('Access is denied') > -1) {
      request = new XDomainRequest();
      request.open('POST', url);
    } else {
      throw err;
    }
  }
  request.send(JSON.stringify(data));
}

哪个工作正常。然后我遇到了this article。它建议这样:

function post(url, data) {
  var request = new XMLHttpRequest();
  if ('withCredentials' in request) {
    request.open('POST', url, true);
    request.setRequestHeader('Content-Type', 'text/plain');
  } else if (typeof XDomainRequest !== 'undefined') {
    console.log('here') // 'here' in IE8,9
    request = new XDomainRequest();
    request.open('POST', url);
  } else {
    throw new Error('XHR cannot handle CORS and XDR is not available');
  }
  request.send(JSON.stringify(data));
}

也应该没事。但是,当我查看网络的标头时,try/catch解决方案给了我:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9YWG9zVC5wbmcifQ==” alt =“在此处输入图像描述”>

[if ('withCredentials' in request)期间:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS90U0xkcy5wbmcifQ==” alt =“在此处输入图像描述”>

他们有不同的Content-Type: text/plain!有人知道为什么吗?

ajax internet-explorer internet-explorer-8 internet-explorer-9
1个回答
0
投票

else if (typeof XDomainRequest !== 'undefined')代码块中,未设置内容类型,由于您正在使用IE8 / 9,因此将执行此块。

© www.soinside.com 2019 - 2024. All rights reserved.