How to call cross domain api network 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"); } }); 

he warns of success, but the data was blank. Url returns xml data, if we specify dataType, we can get json data, but here it did not receive any data.

Any help was appreciated.

+6
source share
4 answers

Javascript obeys the same domain policy. This means that JS Script in the client’s browser can only work in the same domain as it is.

JSONP does not fall under the same restrictions.

Check out jQuery docs for JSONP here:

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

Here is an example of using JSONP to access a cross-domain service through jQuery AJAX:

http://jsbin.com/idasay/4

And just in case, JSBIN will remove 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"); } }); 
+9
source

It is not possible to use Ajax to obtain cross-domain data directly without changing the server side. This is called the same origin policy .

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

+2
source

Look for the jsonp data type.

 jQuery.ajax({ type: "GET", url: 'http://xxx.com/restaurant/VeryLogin(username,password)', dataType: "jsonp", cache: false, crossDomain: true, processData: true, success: function (data) { alert(data); }, error: function (XMLHttpRequest, textStatus, errorThrown) { alert("error"); } }); 
0
source

here is a fantastic article to make cross-domain GET and POST calls: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

It just helped me ... make comments for any request.

0
source

Source: https://habr.com/ru/post/911755/


All Articles