Why does this cross-domain request work in other browsers but not IE9?

前端 未结 3 1200
醉话见心
醉话见心 2021-01-01 00:15

I have some Ajax code that is working in Safari, Chrome and Firefox but not in IE9.

The page is on http://foo.com/test.aspx and it\'s making an AJAX r

相关标签:
3条回答
  • 2021-01-01 00:40

    If this works in the other browsers (which support CORS), then your SVC seems to already be supporting this, but to be sure, use Fiddler2 to see what is going on.

    The Access-Control-Allow-Origin header is used on the resource being requested, not on the page requesting it.

    0 讨论(0)
  • 2021-01-01 00:53

    i just wrestled with the same problem.

    php backend, right mime and yes,

    header('Access-Control-Allow-Origin: *');
    

    worked in almost* every browser - except IE9.

    seems like jQuery.getJSON doesn't automatically do XDR for ie9 - after creating a service proxy on the same domain, it worked.

    * almost - opera acts up too.

    edit: okay, opera did have the same problem as ie9. works like a charm now.

    note: chrome, safari and the firefoxes (3.6-5) had no problem with the cross domain requests with ACAO:*.

    what i don't understand is why a) microsoft uses a different object for cross domain requests and b) why jquery doesn't switch transparently (or at least provide an option to choose).

    0 讨论(0)
  • 2021-01-01 00:55

    Instead of $.ajax(), use this custom code:

    function newpostReq(url,callBack)
    {
        var xmlhttp;
        if (window.XDomainRequest)
        {
            xmlhttp=new XDomainRequest();
            xmlhttp.onload = function(){callBack(xmlhttp.responseText)};
        }
        else if (window.XMLHttpRequest)
            xmlhttp=new XMLHttpRequest();
        else
            xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        xmlhttp.onreadystatechange=function()
        {
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
                callBack(xmlhttp.responseText);
        }
        xmlhttp.open("GET",url,true);
        xmlhttp.send();
    }
    

    Note: this works for GET requests.

    To adapt it on POST requests change the following lines:

    function newpostReq(url,callBack,data)
    

    data is the URL encoded parameters of the post requests such as : key1=value1&key2=value%20two

        xmlhttp.open("POST",url,true);
        try{xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");}catch(e){}
        xmlhttp.send(data);
    

    To summarize, open the connection as POST request (Line 1), set the request header for urlencoded type of the post data (wrap it with try-catch for exceptional browsers) (Line 2), then send the data (Line 3).

    0 讨论(0)
提交回复
热议问题