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!
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.
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 acallback
parameter in the URL. (Of course if you have access you can addJSONP
support too.)If you don't have access to make changes to 'SomeSite' and it supports neither
CORS
norJSONP
, you might be able to useYQL
wp, home as a proxy. It does support bothCORS
andJSONP
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.)