开发者

jQuery Ajax from child domain

I need to make a XHR from a child domain, for instance child.api.com -> api.com. Normally that can be done by setting the document.domain attribute to the same base domain (api.com).

   1. $.ajax({
   2.               url: url,
   3.               data: [],
   4.               beforeSend: function(jqXHR,settings){
   5.                   document.domain = 'api.com';
   6.                   console.log('before send:' + document.domain);
   7.               },
   8.               success: function(resp){
   9.                   console.log('success!');
  10.               },
  11.               error: function(jqXHR,textStatus,errorThrown){
  12.                   console.log('error: '+jqXHR.responseText);
  13.               },
  14.               dataType: 'json'
  15.             });

But this fails. This is the log: before send:api.com XMLHttpRequest cannot load http://api.com/sites/sandbox/users/1/recommendations.json. Origin http://child.api.com is not allowed by Access-Control-Allow-Origin. index.html:56error: recommendations.jsonFailed to load resource

开发者_Python百科

What am I doing wrong?

Greetings, Chielus


Your browser is making a CORS request. Which means the request reaches the server, the server sends the response - as you can observe in Wireshark, the browser checks for Access-Control-Allow-Origin: * header of the response, doesn't find it and blocks response. This is exactly what your error message says: not allowed by Access-Control-Allow-Origin.

What you're doing wrong is assuming that document.domain makes any difference here.

Consider this scenario: you're hosting individual users' blogs on sub-domains, but the account management and posting interface is on your main domain (think Tumblr). If document.domain made any difference for cross-domain requests then I would be able to put some javascript on my blog and post spam to your blog (assuming you're authenticated with the service), and no CSRF protection would stop me.

What document.domain applies to is cross-frame communication. e.g. you can load a page from api.com into iframe on your top page, that iframe page should set document.domain = 'api.com' explicitly, then you set the top page's document.domain = 'api.com', and voila, you can pass data between your top page and the iframe, call functions, and ask the irfame page to make an ajax requests to api.com for you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜