Difficulty with AJAX and JSONP

Asked

Viewed 1,107 times

2

I’m having a problem returning ajax with jsonp, it returns json, but I can’t work with it.

Code:

$.ajax({
    method: "GET",
    url: "http://minasul.tecnologia.ws/previsao/index.php?tipo=TODAS",  
    async: false,
    contentType: "application/json",
    dataType: 'jsonp',
    success: function(json) {
        //QUANDO USO O SUCCESS, ELE NÃO ENTRA AQUI NESSE BLOCO
        //QUANDO USO O COMPLETLE, ELE ENTRA, MAS NÃO CONSIGO TRABALHAR COM O JSON
    }
});

Jsfiddle

  • blz.. I put!

  • What happens if you leave the dataType: 'json' and remove the contentType?

  • so... he from the bug Cros Domain.... you saw that he returns the json blzinha?

  • Good crowd... I have solved the problem by ultilizing this link http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

2 answers

0

Friend, perhaps your difficulty is similar to what I was having. Instead of using $.ajax utilize $.getJSON.

For some reason even I include in Header the properties (Access-Control-Allow-Origin","*") and ("Access-Control-Allow-Methods", "GET, POST") you’re still in error.

Try it this way:

 $.getJSON('Endereco_do_endpoint', function (data) {
 
      //Percorrer pelos itens retornados
      $.each(data, function (key, item) {
        console.log(item.ID);
      });
 });

0

In your page where it is executed select vc should give an echo jsonencode. Example:

 $query = 'SELECT * FROM TABELA';
echo json_encode($query->result());

Soon you can get the result in your ajax.

$.ajax({
    type: "POST",
    url: "http://minasul.tecnologia.ws/previsao/index.php?tipo=TODAS",  
    async: false,
    dataType: 'json',
    success: function(data) {
       console.log(data);
    }
});
  • then.. I’ll put my php code here: Function download_page($path){ $ch = curl_init(); curl_setopt($ch, CURLOPT_URL,$path); curl_setopt($ch, CURLOPT_FAILONERROR,1); curl_setopt($ch, CURLOPT_FOLOWLOCATION,1); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); $retValue = curl_exec($ch); curl_close($ch); Return $retValue; }

  • $cities = array(1162, 1288, 1354, 1567, 1871, 3318, 3637, 5442, 5599); $units = array(); foreach ($cities as $Cod => $value){ $url = "http:/servicos.cptec.inpe.br/XML/city/". $value." /preview.xml"; $units[] = new Simplexmlelement(download_page($url); } echo json_encode($units);

Browser other questions tagged

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