Cross-subdomain AJAX works in Chrome, not IE

老子叫甜甜 提交于 2019-12-09 23:03:01

问题


I have a local build of my site running at local.mydomain.com. I'm making ajax requests to api.mydomain.com which is running on an AWS server and returns JSON. In Chrome, I can call the API no problem. But in IE, I get Access Denied.

After researching, it seems to be a cross-(sub)domain restriction. But I was under the impression that this restriction would apply to both browsers. Can anybody see what might be going wrong here and why it might work in some browsers and not others?


回答1:


It looks like the problem was in the transport object that IE8+ wants you to use. jQuery uses either ActiveXObject (for IE) or XMLHttpRequest (all others), but IE 8 and above requires XDomainRequest for ajax.

What you can do is return a custom xhr object via $.ajaxSettings.xhr like this,

// override xhr for browser that use XDR
if ('XDomainRequest' in window && window.XDomainRequest !== null) {

  // override default jQuery transport
  jQuery.ajaxSettings.xhr = function() {
      try { return new XDomainRequest(); }
      catch(e) {
        console.log('test'); 
      }
  };

  // also, override the support check
  jQuery.support.cors = true;
}

I pulled this code from a discussion on the subject here: http://graphicmaniacs.com/note/getting-a-cross-domain-json-with-jquery-in-internet-explorer-8-and-later/

Definitely take a look at that if you think you're experiencing the same problem.



来源:https://stackoverflow.com/questions/11143226/cross-subdomain-ajax-works-in-chrome-not-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!