Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to call cross-domain web api using ajax?

jQuery.ajax({
           type: "GET",
           url: 'http://example.com/restaurant/VeryLogin(username,password)',
           dataType: "json",

           success: function (data) {
               alert(data);
           },
           error: function (XMLHttpRequest, textStatus, errorThrown) {
               alert("error");
           }
       });

it alerts success, but data was null. The url returns xml data, if we specify the dataType we can get the json data,but here it was not getting any data.

Any help appreciated.

like image 359
tiru Avatar asked Mar 27 '12 13:03

tiru


2 Answers

It's impossible to use Ajax to get cross-domain data directly without changing backend. It's called Same origin policy.

You can set the special header Access-Control-Allow-Origin in backend(how do to this). Or you can use JSONP.

like image 35
Lai Yu-Hsuan Avatar answered Nov 14 '22 11:11

Lai Yu-Hsuan


Javascript is subject to the same domain policy. This means for security a JS Script in a client browser can only access the same domain as it came from.

JSONP is not subject to the same restrictions.

Check the jQuery docs on JSONP here:

http://api.jquery.com/jQuery.getJSON/

Here is a working example of using JSONP to access a cross-domain service via JQuery AJAX:

http://jsbin.com/idasay/4

And just in case JSBIN deletes this paste in the future:

jQuery.ajax({
     type: "GET",
     url: 'http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo',
     dataType: "jsonp",
     cache: false,
     crossDomain: true,
     processData: true,


     success: function (data) {
         alert(JSON.stringify(data));
     },
     error: function (XMLHttpRequest, textStatus, errorThrown) {
         alert("error");
     }
 });
like image 109
pmckeown Avatar answered Nov 14 '22 10:11

pmckeown