JSON: How do I make cross-domain JSON call

2019-01-07 17:01发布

I try to run the following jquery code in local Network.

 $.ajax({
     type: "GET",
     url: "http://SomeSite/MyUrl/",
     cache: false,
     data: { ... },
     dataType: "json",

     error: function (xhr, status, error) {
                                    ... 
     },
     success: function (json) {
                                    ...
     });

Everything works fine until "SomeSite" is localhost. I mean the same server from what the page was downloaded.

But when 'SomeSite' is another (not localhost) network site it looks like request hangs. Not "error", nor "success" callback functions are called. How can I make this code work?

Thank you in advance!

8条回答
时光不老,我们不散
2楼-- · 2019-01-07 17:34

Due to the same origin policy you can't do this. One workaround is to use the Flash AJAX jQuery plugin http://flxhr.flensed.com/ that uses a Flash movie to bypass the same-origin policy.

The other options are to proxy the requests through your own domain or use JSONP.

查看更多
可以哭但决不认输i
3楼-- · 2019-01-07 17:36

Do you have server access to 'SomeSite', or is it 3rd party?

  • If you have access you can enable CORS wp, home on it. In its simplest form (data is not session sensitive), just add the header: Access-Control-Allow-Origin: *

  • If you don't have access do you know whether it supports JSONP wp, so? This typically involves passing at least a callback parameter in the URL. (Of course if you have access you can add JSONP support too.)

  • If you don't have access to make changes to 'SomeSite' and it supports neither CORS nor JSONP, you might be able to use YQL wp, home as a proxy. It does support both CORS and JSONP and can even translate data formats, select some part of the data, etc.
    (Note that YQL respects robots.txt so if it's a 3rd party site that restricts automated access you might still be out of luck.)

查看更多
登录 后发表回答