Problem consuming Json with javascript

Asked

Viewed 73 times

1

I’m trying to consume this link

http://wsloterias.azurewebsites.net/api/sorteio/getresultado/1

with that method:

$.getJSON("http://wsloterias.azurewebsites.net/api/sorteio/getresultado/1",   function (json) {
    alert(1);
});

But it doesn’t read.. I tested with other sites and it worked. I have to call some other method or something like?

1 answer

3


The problem is that the server/page you are trying to consume the data from does not have any authorization, Access-Control-Allow-Origin, to send the data to the server that is requesting it with the ajax request... That is, the problem is not in the request (ajax) but in the requested API, which does not accept to respond to ajax requests coming from other domains.

Error on console:

No 'Access-Control-Allow-Origin' header is present on the requested Resource

To solve, assuming you have access to the server-side code of the api, you must authorize all or only a few domains to get the right answer, depending on the server-side language you can give this authorization, in case it is php:

at the top of the requested php script you can:

authorize all:

header('Access-Control-Allow-Origin: *');

authorise only a few, in this case the field exemplo1.com and exemplo2.com are allowed to receive via ajax the data:

header('Access-Control-Allow-Origin: http://www.exemplo1.com', false);
header('Access-Control-Allow-Origin: http://www.exemplo2.com', false);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.