开发者

How to make cross domain XHR request

How to make working XHR cross domain request - I've tried 'Script Tag Hack' but it doesn't work or I'm doing something wrong. Any suggestions?

I would like to call script in domain A from B.

domain A: [index.html]

<head>
<script type="text/javascript" src="https://evilDomain/xhrTest.js"></script>
</head>

domain B: [xhrTest.js]

$.ajax({
      url: "https://evilDomain/processRequest",
      success: function(result){
        alert(result);
      }
});

edited:

I've also tried to use JSONP in this way:

$.ajax({
      url: "https://evilDomain/processRequest",
      dataType: "jsonp",
      success: function(result){
        alert(result);
      }
});

I'm using TOMCAT con开发者_高级运维tainer, is the solution connected with Access-Control-Allow-Origin header?


Yes, you can add the Access-Control-Allow-Origin header to your server responses. This will allow you to make cross-domain requests.

You can then further customise as required with Access-Control-Allow-Methods and Access-Control-Allow-Headers.

For more details see https://developer.mozilla.org/en/HTTP_access_control


Usually, you would ask your server to do the request for you.

The other option is to let someone else do that for you (such as Yahoo's service).

Your problem is that domain B's code is still executed in the context of domain A. Hence, https://evilDomain/processRequest still cannot be read because the code is executing as domain A even if in truth it came from domain B.


use JSONP or have a service on your own domain call the other domain on the server-side and get what you need that way.


The domain B JS is being included in the page, then being executed from the page which originates from domain A, hence the problem. To do this cross domain you need to request the data response as a "script" itself, then parse it from there.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜