IE9使用带有CORS的jQuery AJAX出现“访问被拒绝”错误

123

以下内容在所有浏览器中均有效,除了IE(我正在测试IE 9)。

jQuery.support.cors = true;
...
        $.ajax(
            url + "messages/postMessageReadByPersonEmail",
            {
                crossDomain: true,
                data: {
                    messageId       : messageId,
                    personEmail     : personEmail
                },
                success: function() {
                    alert('marked as read');
                },
                error: function(a,b,c) {
                    alert('failed');
                },
                type: 'post'
            }
        );

我有另一个使用 dataType: 'jsonp' 的函数,但我不需要在这个 AJAX 调用中返回任何数据。我的最后一招将是返回一些包装在 JSONP 中的胡言乱语,只是为了让它正常工作。

有没有想法为什么 IE 会在返回没有数据的 CORS 请求时出错?


由于所有提供的答案都对我无效(我还必须将cookie传递到CORS请求中,但在使用XDomainRequest时这是不允许的),因此这里有一个解决方法:http://blog.gauffin.org/2014/04/how-to-use-cors-requests-in-internet-explorer-9-and-below/。代理拯救了我!:p - wimvds
12个回答

0
我在我的开发机上测试CORS Web服务时,在IE中只收到“访问被拒绝”的错误消息。Firefox和Chrome都正常工作。原来这是由于我在ajax调用中使用了localhost引起的!因此,我的浏览器URL类似于:

http://my_computer.my_domain.local/CORS_Service/test.html

我的test.html页面里的ajax调用大概是这样的:

//fails in IE 
$.ajax({
  url: "http://localhost/CORS_Service/api/Controller",
  ...
});

一旦我将ajax调用更改为使用我的计算机IP而不是localhost,一切都正常工作。

//Works in IE
$.ajax({
  url: "http://192.168.0.1/CORS_Service/api/Controller",
  ...
});

IE开发工具窗口的“网络(Network)”选项卡还显示了CORS Preflight OPTIONS请求,然后是XMLHttpRequest GET请求,这正是我希望看到的。

-1

注意 -- 注意

在ajax中不要使用 "http://www.domain.xxx" 或 "http://localhost/" 或 "IP >> 127.0.0.1" 作为URL地址。 只需使用路径(目录)和页面名称,不需要地址。

错误状态:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir/getSecurityCode.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);

真实状态:

var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'dir/getSecurityCode.php', true);   // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接