IE跨域ajax调用XDomainRequest错误

时间:2012-09-25 17:26:23

标签: internet-explorer jquery cross-domain xdomainrequest

我必须使用以下代码从iframe中的页面注销

//The javascript code is in a page in my-domain
//it tries to logout from the page in other-domain
$(window).unload(function() 
{
    if ($.browser.msie && window.XDomainRequest) // IE
    {
        var xdr = new XDomainRequest();
        if (xdr)
        {
            xdr.onerror = function(){alert("XDR onerror");};
            xdr.ontimeout   = function(){alert("XDR timeout");};
            xdr.onprogress  = function(){alert("XDR onprogress");};
            xdr.onload      = function(){alert("XDR onload");};
            xdr.timeout     = 5000;
            xdr.open("GET", 'http://other-domain/.../j_spring_security_logout');
            alert("before send");
            xdr.send();
            alert("after send");
        }
        else
            alert('Failed to create new XDR object.');
    } 
    else // firefox
       $.getJSON( 'http://other-domain/.../j_spring_security_logout?callback=?', null);

}); 

但是,我按照以下顺序在IE8中获得了改动框:“发送前”,“XDR onerror”,“发送后”。

我在服务器端有以下代码

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
    response.setHeader("Access-Control-Max-Age", "360");
    response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
    chain.doFilter(req, res);
}

在使用$ .getJSON和response.setHeader(“Access-Control-Allow-Origin”,“*”)等之后,我可以验证注销是否适用于Firefox;但是当我使用IE时它不会注销。

然后我在网上发现了这条评论:

"For cross-domain, IE requires you to use XDomainRequest instead of XMLHttpRequest.
 jQuery doesn't do it so you have to do it manually:"

所以我添加了XDomainRequest。但是,我在IE8中收到了警告对话框“XDR onerror”。我应该添加什么才能在IE中进行跨域调用?

2 个答案:

答案 0 :(得分:1)

尝试使用iframe发出XDomainGet请求:

root = document.body;

myIframe = document.createElement("iframe");
myframe.setAttribute("id", "myFrameId")
myIframe.setAttribute("style", "position: absolute; top: -100px;");
//Making a xget
myIframe.setAttribute("src", "http://other-domain.../j_spring_security_logout?callback=?");

root.appendChild(myframe);

删除do:     document.body.removeChild(document.getElementById(“myFrameId”)); 要么     root.removeChild(myFrame);

答案 1 :(得分:0)

可以使用jQuery插件jquery-transport-xdr

启用IE8 / 9中的

CORS 请求