【问题标题】:Why IE9 (8) treat XDR differently with try/catch为什么 IE9 (8) 用 try/catch 区别对待 XDR
【发布时间】:2015-02-26 18:06:04
【问题描述】:

所以我想在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 解决方案给了我:

if ('withCredentials' in request):

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

【问题讨论】:

  • 一位前 IE 开发人员在这篇博文中的第 4 点有一个有趣的评论:blogs.msdn.com/b/ieinternals/archive/2010/05/13/… 它说:“注意:截至 2014 年,XDomainRequest 似乎没有发送任何 Content-Type 标头完全没有。我不清楚这是什么时候改变的。”我完全推测性的猜测是 XDR 是错误的,并且某些使用模式会导致它设置标题或没有以未记录的方式设置它。

标签: ajax internet-explorer internet-explorer-8 internet-explorer-9


【解决方案1】:

else if (typeof XDomainRequest !== 'undefined') 代码块中没有设置内容类型,因为你使用的是 IE8/9,所以这个块将被执行。

【讨论】:

  • 也不应该设置try catch,因为我创建了一个新请求。
  • 你确定有异常抛出?
  • 是的。无论如何,我们正在做一个 cors 请求。 XHR 没有能力。
  • 尝试删除request.setRequestHeader('Content-Type', 'text/plain'); int 他尝试捕获,看看会发生什么。
  • 我发现了问题所在。 IE 将不同的端口视为同一个来源,因此在我的 try/catch 方法中,根本不使用 XDR。如果你调整你的答案,我会标记它是正确的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-09
  • 1970-01-01
  • 2012-11-20
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 2010-12-14
相关资源
最近更新 更多