带有 CORS 的 IE9 jQuery AJAX 返回“访问被拒绝”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10232017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 08:59:20  来源:igfitidea点击:

IE9 jQuery AJAX with CORS returns "Access is denied"

jqueryinternet-explorer-9cross-domainjsonpcors

提问by Garrett

The following works in all browsers except IE(I'm testing in IE 9).

以下适用于除 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'
            }
        );

I have another function which uses dataType: 'jsonp', but I don't need any data returned on this AJAX call. My last resort will be to return some jibberish wrapped in JSONP just to make it work.

我有另一个使用 的函数dataType: 'jsonp',但我不需要在此 AJAX 调用中返回任何数据。我最后的手段是返回一些包裹在 JSONP 中的胡言乱语,以使其工作。

Any ideas why IE is screwing up with a CORS request that returns no data?

任何想法为什么 IE 会搞砸一个不返回数据的 CORS 请求?

回答by dennisg

This is a known bugwith jQuery. The jQuery team has "no plans to support this in core and is better suited as a plugin." (See this comment). IE does notuse the XMLHttpRequest, but an alternative object named XDomainRequest.

这是jQuery 的一个已知错误。jQuery 团队“没有计划在核心中支持它,更适合作为插件。” (请参阅此评论)。IE浏览器无法使用XMLHttpRequest的,但命名的替代对象XDomainRequest

There isa plugin available to support this in jQuery, which can be found here: https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

还有就是可以支持这jQuery的一个插件,它可以在这里找到https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js

EDITThe function $.ajaxTransportregisters a transporter factory. A transporter is used internallyby $.ajaxto perform requests. Therefore, I assumeyou should be able to call $.ajaxas usual. Information on transporters and extending $.ajaxcan be found here.

编辑该函数$.ajaxTransport注册一个转运工厂。甲转运用于内部$.ajax执行请求。因此,我认为您应该可以$.ajax像往常一样打电话。$.ajax可以在此处找到有关传输器和扩展的信息。

Also, a perhaps better version of this plugin can be found here.

此外,可以在此处找到此插件的更好版本。

Two other notes:

另外两个注意事项:

  1. The object XDomainRequest was introduced from IE8and will not work in versions below.
  2. From IE10 CORS will be supported using a normal XMLHttpRequest.
  1. 对象 XDomainRequest 是从 IE8 引入的,在以下版本中不起作用。
  2. 从 IE10 开始,将使用普通的 XMLHttpRequest 支持CORS 。

Edit 2: http to https problem

编辑 2:http 到 https 问题

Requests must be targeted to the same scheme as the hosting page

This restriction means that if your AJAX page is at http://example.com, then your target URL must also begin with HTTP. Similarly, if your AJAX page is at https://example.com, then your target URL must also begin with HTTPS.

请求必须针对与托管页面相同的方案

此限制意味着如果您的 AJAX 页面位于 http://example.com,那么您的目标 URL 也必须以 HTTP 开头。同样,如果您的 AJAX 页面位于https://example.com,那么您的目标 URL 也必须以 HTTPS 开头。

Source: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

来源:http: //blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

回答by HymanMorrissey

Building off the accepted answer by @dennisg, I accomplished this successfully using jQuery.XDomainRequest.jsby MoonScript.

根据@dennisg 接受的答案,我使用MoonScript的 jQuery.XDomainRequest.js成功完成了这项工作。

The following code worked correctly in Chrome, Firefox and IE10, but failed in IE9. I simply included the script and it now automagically works in IE9. (And probably 8, but I haven't tested it.)

以下代码在 Chrome、Firefox 和 IE10 中正常运行,但在 IE9 中失败。我只是简单地包含了脚本,它现在可以在 IE9 中自动运行。(可能是 8 个,但我还没有测试过。)

var displayTweets = function () {
    $.ajax({
        cache: false,
        type: 'GET',
        crossDomain: true,
        url: Site.config().apiRoot + '/Api/GetTwitterFeed',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function (data) {
            for (var tweet in data) {
                displayTweet(data[tweet]);
            }
        }
    });
};

回答by MoonScript

Complete instructions on how to do this using the "jQuery-ajaxTransport-XDomainRequest" plugin can be found here: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest#instructions

可以在此处找到有关如何使用“jQuery-ajaxTransport-XDomainRequest”插件执行此操作的完整说明:https: //github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest#instructions

This plugin is actively supported, and handles HTML, JSON and XML. The file is also hosted on CDNJS, so you can directly drop the script into your page with no additional setup: http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js

该插件受到积极支持,可处理 HTML、JSON 和 XML。该文件也托管在 CDNJS 上,因此您可以直接将脚本放入您的页面而无需额外设置:http: //cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest .min.js

回答by jgauffin

The problem is that IE9 and below do not support CORS. XDomainRequest do only support GET/POST and the text/plainconten-type as described here: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

问题是IE9及以下不支持CORS。XDomainRequest 只支持 GET/POST 和text/plain这里描述的内容类型:http: //blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

So if you want to use all HTTP verbs and/or json etc you have to use another solution. I've written a proxy which will gracefully downgrade to proxying if IE9 or less is used. You do not have to change your code at all if you are using ASP.NET.

因此,如果您想使用所有 HTTP 动词和/或 json 等,您必须使用另一种解决方案。我编写了一个代理,如果使用 IE9 或更低版本,它将优雅地降级为代理。如果您使用的是 ASP.NET,则根本不必更改代码。

The solution is in two parts. The first one is a jquery script which hooks into the jQuery ajax processing. It will automatically call the webserver if an crossDomain request is made and the browser is IE:

解决方案分为两部分。第一个是一个 jquery 脚本,它与 jQuery ajax 处理挂钩。如果发出跨域请求并且浏览器是 IE,它将自动调用 web 服务器:

$.ajaxPrefilter(function (options, originalOptions, jqXhr) {
    if (!window.CorsProxyUrl) {
        window.CorsProxyUrl = '/corsproxy/';
    }
    // only proxy those requests
    // that are marked as crossDomain requests.
    if (!options.crossDomain) {
        return;
    }

    if (getIeVersion() && getIeVersion() < 10) {
        var url = options.url;
        options.beforeSend = function (request) {
            request.setRequestHeader("X-CorsProxy-Url", url);
        };
        options.url = window.CorsProxyUrl;
        options.crossDomain = false;
    }
});

In your web server you have to receive the request, get the value from the X-CorsProxy-Url http header and do a HTTP request and finally return the result.

在您的 Web 服务器中,您必须接收请求,从 X-CorsProxy-Url http 标头中获取值并执行 HTTP 请求并最终返回结果。

My blog post: http://blog.gauffin.org/2014/04/how-to-use-cors-requests-in-internet-explorer-9-and-below/

我的博文:http: //blog.gauffin.org/2014/04/how-to-use-cors-requests-in-internet-explorer-9-and-below/

回答by yanni

Building on the solution by MoonScript, you could try this instead:

基于 MoonScript 的解决方案,您可以试试这个:

https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

https://github.com/intuit/xhr-xdr-adapter/blob/master/src/xhr-xdr-adapter.js

The benefit is that since it's a lower level solution, it will enable CORS (to the extent possible) on IE 8/9 with other frameworks, not just with jQuery. I've had success using it with AngularJS, as well as jQuery 1.x and 2.x.

好处是,由于它是一个较低级别的解决方案,它将在 IE 8/9 上使用其他框架(而不仅仅是使用 jQuery)启用 CORS(在可能的范围内)。我已经成功地将它与 AngularJS 以及 jQuery 1.x 和 2.x 一起使用。

回答by Garrett

I just made all requests JSONPbecause it was the only solution for all of our supported browsers (IE7+ and the regulars). Mind you, your answer technically works for IE9 so you have the correct answer.

我只是提出了所有请求JSONP,因为它是我们所有支持的浏览器(IE7+ 和常规浏览器)的唯一解决方案。请注意,您的答案在技术上适用于 IE9,因此您有正确的答案。

回答by jmarcosSF

Getting a cross-domain JSON with jQuery in Internet Explorer 8 and newer versions

在 Internet Explorer 8 和更新版本中使用 jQuery 获取跨域 JSON

Very useful link:

非常有用的链接:

http://graphicmaniacs.com/note/getting-a-cross-domain-json-with-jquery-in-internet-explorer-8-and-later/

http://graphicmaniacs.com/note/getting-a-cross-domain-json-with-jquery-in-internet-explorer-8-and-later/

Can help with the trouble of returning json from a X Domain Request.

可以帮助解决从 X 域请求返回 json 的麻烦。

Hope this helps somebody.

希望这可以帮助某人。

回答by Bernard

Update as of early 2015. xDomain is a widely used library to supports CORS on IE9 with limited extra coding.

2015 年初更新。xDomain 是一个广泛使用的库,用于支持 IE9 上的 CORS,但额外编码有限。

https://github.com/jpillora/xdomain

https://github.com/jpillara/xdomain

回答by hacklover

To solve this problem, also check if you have some included .js into your ajax file called: I received Access denied error while including shadowbox.js in my ajax.php

要解决此问题,还要检查您的 ajax 文件中是否包含一些包含的 .js 文件,名为:我收到访问被拒绝错误,同时在我的 ajax.php 中包含 shadowbox.js

回答by jwill212

I was testing a CORS web service on my dev machine and was getting the "Access is denied" error message in only IE. Firefox and Chrome worked fine. It turns out this was caused by my use of localhost in the ajax call! So my browser URL was something like:

我正在我的开发机器上测试 CORS Web 服务,并且仅在 IE 中收到“访问被拒绝”错误消息。Firefox 和 Chrome 运行良好。原来这是我在 ajax 调用中使用 localhost 造成的!所以我的浏览器 URL 是这样的:

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

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

and my ajax call inside of test.html was something like:

我在 test.html 中的 ajax 调用类似于:

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

Everything worked once I changed the ajax call to use my computer IP instead of localhost.

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

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

The IE dev tools window "Network" tab also shows CORS Preflight OPTIONS request followed by the XMLHttpRequest GET, which is exactly what I expected to see.

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