ajax – 为什么这个跨域请求在其他浏览器中工作但在IE9中不起作用?

我有一些Ajax代码可以在Safari,Chrome和Firefox中使用,但不能在IE9中使用.

页面位于http://foo.com/test.aspx,它正在向https://service.foo.com上托管的Web服务发出AJAX请求.我以为我不会有任何跨域问题,但鉴于IE9阻止它,它似乎我做:(

var tempurl = "https://service.foo.com/dummy.svc/test?hi=bye";
$.get(tempurl,"html");

正如我所提到的,代码可以在其他3个浏览器中运行,而不是IE9. (我只关心IE9,而不是IE8或更老版本).

我做了一些挖掘,在MSDN上找到this article说:

Cross-domain requests require mutual
consent between the Web page and the
server. You can initiate a
cross-domain request in your Web page
by creating an XDomainRequest object
off the window object and opening a
connection to a particular domain. The
browser will request data from the
domain’s server by sending an Origin
header with the value of the origin.
It will only complete the connection
if the server responds with an
Access-Control-Allow-Origin header of
either * or the exact URL of the
requesting page. This behavior is part
of the World Wide Web Consortium
(W3C)’s Web Application Working
Group’s draft framework on client-side
cross-domain communication that the
XDomainRequest object integrates with.

在我走下使用XDR的道路之前,我想与比我更聪明的人验证这是否是正确的方法.

>添加response.addheader(“Access-Control-Allow-Origin”,“*”);到我的页面
>创建检测IE9的条件jscript代码并使用XDR而不是我正在使用$.get的常规jquery调用.

我完全不在或者这是正确的方法吗?

(假设这是正确的方法,Acecss-Control-Allow-Origin响应标题http://foo.com/test.aspx或在https://service.foo.com的网络服务上去了?)

而不是$.ajax(),使用此自定义代码
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();
}

注意:这适用于GET请求.

要在POST请求上进行调整,请更改以下行:

function newpostReq(url,callBack,data)

data是post请求的URL编码参数,例如:key1 = value1& key2 = value two

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

总而言之,打开连接作为POST请求(第1行),设置postlen数据的urlencoded类型的请求标头(用特殊浏览器的try-catch包装)(第2行),然后发送数据(第3行).

相关文章

IE6是一个非常老旧的网页浏览器,虽然现在很少人再使用它,但...
PHP中的count()函数是用来计算数组或容器中元素的个数。这个...
使用 AJAX(Asynchronous JavaScript and XML)技术可以在不...
Ajax(Asynchronous JavaScript and XML)是一种用于改进网页...
本文将介绍如何通过AJAX下载Excel文件流。通过AJAX,我们可以...
Ajax是一种用于客户端和服务器之间的异步通信技术。通过Ajax...