Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
519 views
in Technique[技术] by (71.8m points)

jquery - JSON: How do I make cross-domain JSON call

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I had the same issue. Trying to get json from a server to wich I dind't had access (=> no JSONP).

I found http://benalman.com/projects/php-simple-proxy/ Add the php proxy to your server and do the ajax call to this file.
"Any GET parameters to be passed through to the remote URL resource must be urlencoded in this parameter."

$.ajax({
   type: 'GET',
   url:'proxy.php?url=http://anyDomain.com?someid=thispage',
   dataType: "json",
   success: function(data){
      // success_fn(data);
   },
   error: function(jqXHR, textStatus, errorThrown) {
      // error_fn(jqXHR, textStatus, errorThrown);
   }
});

where proxy.php (the file from Ben Alman) is hosted in your domain



Alternative (which I found to be second best to this):
http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...