How to receive a JSON object from an external url/domain?

Asked

Viewed 10,935 times

6

I found a Lottery API that brings me the data of the result of a Lotofácil draw, but I am not able to access the data of the JSON object.

I’m trying this way:

$(document).ready(function(){
    $.get( "http://developers.agenciaideias.com.br/loterias/lotofacil/json", function( data ) {
      $( ".result" ).html( data );
      alert( "Load was performed." );
    });
}); 

But the browser console shows me this error:

Xmlhttprequest cannot load http://developers.agenciaideias.com.br/loterias/lotofacil/json. In the 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.

When I directly access the URL I download the JSON file normally, then I would like to know what this error is about and how to make the right call to receive this data.

  • you tried using jsonp ?

  • I read about it, but I was in doubt in the implementation because I only saw example with POST and not with GET.

  • With jsonp it can access but from the other error: Uncaught Syntaxerror: Unexpected token : Developers.agenciaideias.com.br/lotteries/lotofacil/json? callback=jQuery1110... 82617&_=14141731373&callback=jQuery111003546048323623836_14141731372:1

  • 1

    I was testing several methods the other day to get around this limitation and I even found one that worked on some websites. As it did not work on the site I wanted, I left aside; I think it was using a proxy of Yahoo. I will try to locate here.

6 answers

5

This answer says Javascript code is limited by security policy same-origin policy.

That is, what you are trying to do (get content from another domain via Javascript) is browser-locked.

Still according to the same answer, in order to be possible this type of access you would need a configuration in the target domain (Agents.agenciaideias.com.br).

That is: you cannot obtain this content from Javascript running in the browser. You will have to get on the server side of your application and return to your user a page ready with content.

  • So if I try via PHP for example I’ll probably get?

  • 1

    If there is no specific lock in the target application (Agents.agenciaideias.com.br) such as requiring authentication that you don’t have, yes, you will.

  • Your tip killed the puzzle, I received object via PHP and I was able to capture the information.

5

It is possible to use the Yahoo Query Language dribble some cases of Same-origin Policy.

Example:

$.getJSON("http://query.yahooapis.com/v1/public/yql",
{
    q: 'select * from json where url="http://developers.agenciaideias.com.br/loterias/lotofacil/json"',
    format: "json"
},
function(data){
    if (data.query.results) {
        console.log('data',data.query.results.json)
    } else {
        console.error('no results')
    }
});

Prints:

{
  "concurso": {
    "numero": "1122",
    "data": "ES",
    "cidade": "<span style=\"font-size: 12px; font-weight: bold;\">Estimativa de Prêmio</span><br /><span style=\"color: rgb(102, 102, 102); font-size: 22px; font-weight:bold;\">R$</span> <span style=\"font-size: 22px; color:#911687; font-weight: bold;\">1.700.000,00</span><br /><span style=\"font-size: 11px;\">*para o próximo concurso, a ser realizado em 24/10/2014</span><br /><br />-<a href=\"javascript:imprimir_lotofacil(1122);\"><img src=\"/loterias/_images/button/btn_imprimir_resultadojogo.jpg\" width=\"148\" height=\"73\" border=\"0\" /></a>",
    "local": "Caminhão da Sorte",
    "numeros_sorteados": [
      "02",
      "03",
      "07",
      "10",
      "11",
      "12",
      "13",
      "14",
      "16",
      "19",
      "20",
      "21",
      "23",
      "24",
      "25"
    ],
    "premiacao": {
      "acertos_15": {
        "ganhadores": "4",
        "valor_pago": "428.378,51"
      },
      "acertos_14": {
        "ganhadores": "507",
        "valor_pago": "1.485,58"
      },
      "acertos_13": {
        "ganhadores": "19.267",
        "valor_pago": "15,00"
      },
      "acertos_12": {
        "ganhadores": "242.287",
        "valor_pago": "6,00"
      },
      "acertos_11": {
        "ganhadores": "1.252.543",
        "valor_pago": "3,00"
      }
    }
  },
  "proximo_concurso": {
    "data": "23",
    "valor_estimado": "20"
  }
} 

Reference: How to Scrape content from other sites using jQuery?

3


Thanks to Caffé’s response, through PHP I was able to obtain the object and its values, in this way:

$json = file_get_contents('http://developers.agenciaideias.com.br/loterias/lotofacil/json');
$jsonDecode = (json_decode($json, true));

2

The browser protection system does not allow the exchange of xml or json from different domains, however, it allows the use of "link" calls to javascript scripts from external Urls. Using jQuery with dataType type "jsonp" ( with P ); This format informs jQuery to use a "trick" that "tricks" the browsed ;-), since internally the request is made as a "link" of script. I have been using for a long time and IT WORKS!

{
jQuery.ajax({
        url  : 'http://www.respondePaginasWeb',
        data : 'cliente=eu&acao=getmenu',
        type : "GET",
        crossDomain  : "true",
        dataType     : "jsonp",
        contentType  : "application/json",
        success: function( menu ){
            console.log(menu);
        }
    });
}

1

This url is blocked here at work, try something like this to see what:

$.ajax({ 
  url:"http://developers.agenciaideias.com.br/loterias/lotofacil/json", 
  type:"GET", 
  crossDomain: "true", 
  dataType: 'application/json', 
  success: function (d) { 
     console.log(d) 
  }
})

  • I added an error: Function(){ Alert("error")} and it fell into error.

  • what error? could post?

  • I couldn’t catch the bug. I tried to catch it like this but it didn’t show anything: error: Function(xhr, status, error) ? Alert(xhr.responseText);}

0

testarApi();

function testarApi(){

  var token ="crie seu token"
  var sorteio = "";
  $.ajax(
  {
    url: "https://lotorapido1.websiteseguro.com/lotofacil?token="+token+"&sorteio="+sorteio,
    method:'get',
    crossDomain: true,
    beforeSend: function() {
       $('#target').html('loading....');
    },
    success: function (response) {
            $('#target').html(response);
        },
        error: function (error) {
            $('#target').html("['error' => '"+error.statusText+"']");
        }
  });
}    
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<pre id="target"></pre>

Aproveita e testa minha API BETA: https://lotorapido1.websiteseguro.com/

take advantage and test my free lottery API: https://lotorapido1.websiteseguro.com

Browser other questions tagged

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