微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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行).

原文地址:https://www.jb51.cc/ajax/160224.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐