【问题标题】:IE11 XMLRequest Access is DeniedIE11 XMLRequest 访问被拒绝
【发布时间】:2014-07-09 09:01:58
【问题描述】:

我尝试在 http://localhost:8080/ 上执行简单的 AJAX 请求,但在使用 IE 11 时立即收到错误消息。我认为 IE 甚至没有尝试发送任何内容。

有人遇到过这个问题吗?

这是一个 fiddle 显示此行为,

html:

<button id='btn1'>launch</button>

加载:

var xhr,btn=document.getElementById('btn1');
btn.onclick=onButton;

var onReadyState=function(){
  console.log('ready state:'+_xhr.readyState);
  if(xhr.readyState===4){
    console.log('status:'+_xhr.status);
  }
}

function onButton(){
  xhr=new window.XMLHttpRequest();
  xhr.onreadystatechange=onReadyState;
  xhr.open('POST','http://localhost:8080/ScanAPI/v1/client');
  xhr.send();
}

在尝试之前,您需要启动 IE F12 开发人员工具,您会看到 IE 捕获异常。

对此的任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: javascript exception xmlhttprequest cors internet-explorer-11


    【解决方案1】:

    它不起作用,因为您引用了一个名为 _xhr 的对象,该对象不存在于 onReadyState 函数的范围内。

    您应该改用this

    var onReadyState = function() {
        if (this.readyState === 4) {
            console.log('status :' + this.status);
        }
    };
    

    这是因为XMLHttpRequest 对象将使用自己的上下文回调onReadyState,可以通过函数中的this 访问。

    还要注意onReadyState 函数在其定义末尾缺少一个分号,乍一看并没有注意到。

    编辑:我还注意到 IE10(和 IE11)确实解释 some HTTP response code as network errors(例如带有 401 响应代码),如果是您的情况,那么 IE 是有道理的无法检索您的资源。

    我 fork 你的小提琴和wrote a simple page 与 IE11 配合得很好。

    【讨论】:

    • 这点 Halim 很好,但它不会影响结果,因为异常发生在 xhr.open 并且永远不会调用 onReadyState 函数。
    • 您的 Web 服务在出现错误时返回什么错误代码?你能检查一下吗?我编辑了我的回复,还创建了一个与 Chrome 和 IE11 完美配合的小提琴。另外,您确定您没有因 CORS 出现错误(例如,在您的网站中使用 127.0.0.1 而不是 localhost)?
    • 你是对的,使用 127.0.0.1 而不是 localhost 确实有效!
    • 当使用localhost服务没有被请求命中时,在open调用期间发生了异常。当然,这适用于 FireFox 和 Chrome。首先我没有怀疑,因为我对 IE11 和本地 html 文件的初步测试工作正常。当我在不同的服务器上托管 html 文件时,它开始失败。
    猜你喜欢
    • 2015-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-10
    • 2021-03-06
    • 2011-05-15
    • 2010-09-06
    相关资源
    最近更新 更多