简体   繁体   中英

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 container, 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

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.

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM