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

前端 未结 3 1216
醉话见心
醉话见心 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: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).

提交回复
热议问题