2012-09-25 77 views
2

我不得不使用下面的代碼從頁面註銷在的iframeIE跨域AJAX調用XDomainRequest錯誤

//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恐怖」,「發送後」。

我在服務器端下面的代碼

@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); 
} 

我可以確認的是,註銷工作非常適合我的Firefox使用$ .getJSON和response.setHeader(「訪問控制允許來源」之後, 「*「) 等等;但是當我使用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中進行跨域調用?

回答

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); 

要刪除操作: document.body.removeChild(的document.getElementById( 「myFrameId」)); 或 root.removeChild(myFrame);在IE8/9