Problem consuming Json with javascript

1

I'm trying to consume this link

link

with this method:

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

But it does not read .. I tested it with other websites and it worked. Do I have to call some other method or something?

    
asked by anonymous 24.12.2016 / 20:39

1 answer

3

The problem is that the server / page where you are trying to consume the data does not have any authorization, Access-Control-Allow-Origin , to send the data to the server that is requesting them with the ajax request ... In other words , 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.

Console error:

  

In the 'Access-Control-Allow-Origin' header is present on the requested resource

To solve, assuming that you have access to the server-side code of the api, you have to authorize all or only some domains to get the right answer, depending on the language on the server side 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: *');

To allow only a few, in this case the domain 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);
    
24.12.2016 / 20:49