How to perform cross-site ajax request?

前端 未结 3 968
半阙折子戏
半阙折子戏 2021-01-22 14:42

Browsers don\'t allow cross-site AJAX calls (it\'s a security restriction). Is there any possible solution ?

EDIT

I control only the caller website

3条回答
  •  Happy的楠姐
    2021-01-22 14:51

    There are 2 ways to do this, depending on whether the callee will ship out JSONP or not:

    1. If you can, use JSONP

    JSONP is a way to bypass the cross domain policy by returning a function call, rather than a naked JSON object. The P stands for padding, essentially just the part that calls the function.

    For this to work, the callee needs to return JSONP.

    Regular JSON looks like this:

    {a: 12, b: 15}
    

    JSONP looks like this:

    callback({a: 12, b: 15});
    

    When the AJAX request completes, the callback function (which you define in your own code) will be executed and the JSON data passed to it as an object, thus bypassing the cross domain policy.

    2. If JSONP is not supported, mirror the request through your own server

    The second option is to pipe data through your own server. Your JavaScript makes a request from your server, and the server then mirrors that request to the remote server and pings back the result.

    Since the AJAX request is now made to your own server you won't run afoul of the cross domain policy.

    There are two downsides to this approach:

    1. Two requests are now required which will slow the response time a little, though probably not much as server to server communication will probably be via a fat pipe.
    2. Since all requests now originate from your server you may have problems with IP based rate limits. This is the case with Twitter API calls. You may be able to mitigate against this by caching results.

提交回复
热议问题