I cannot retrieve JSON in jQuery

Asked

Viewed 63 times

0

I’m having trouble showing off uf in the following situation:

$.post("<?php echo site_url('Welcome/viacep'); ?>",
    {cep: cep}, 
   function(dados){
       alert(dados.uf); 
    }, 
    'json'
);

But when I change the Alert to alert(dados), the JSON appears complete.

What am I doing wrong?

  • how is your json returning?

  • http://viacep.com.br/ws/30626620/json/{ "cep": "30626-620", "patio": "Rua Joaquim Teixeira Dias", "complement": "", "neighborhood": "Cardoso (Barreiro)", "locality": "Belo Horizonte", "Uf": "MG", "unit": "", "ibge": "3106200", "Gia": ""&#Xa";}

3 answers

0

Maybe you have to parse json:

$.post("<?php echo site_url('Welcome/viacep'); ?>", {cep: cep}, 
    function(response){ 
        var dados = JSON.parse(response);
        alert(dados.uf);
    }
, 'json' );
  • When I call JSON.parse, that’s when nothing works.

  • My json is coming like this:

  • http://viacep.com.br/ws/30626620/json/{ "cep": "30626-620", "patio": "Rua Joaquim Teixeira Dias", "complement": "", "neighborhood": "Cardoso (Barreiro)", "locality": "Belo Horizonte", "Uf": "MG", "unit": "", "ibge": "3106200", "Gia": ""&#Xa";}

  • everything worked out here.

0

You need to convert this JSON that was received as text to a Object. You can use the JSON.parse, same native Javascript, as follows:

let obj = JSON.parse(dados);

The manipulation you use the obj instead of dados.

alert(obj.cep);

jQuery also has a function to deserialize JSON, $.parseJSON, but is considered obsolete, so you can use the pure Javascript as in the example given above.

As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the Native JSON.parse method Instead. Source

0

Try it this way:

$.getJSON("//viacep.com.br/ws/"+ cep +"/json/?callback=?", function(dados) {

        if (!("erro" in dados)) {
            //Atualiza os campos com os valores da consulta.
            $("#logradouro").val(dados.logradouro);
            $("#bairro").val(dados.bairro);
        } //end if.
        else {
            //CEP pesquisado não foi encontrado.
            //limpa_formulário_cep();
            errosend("CEP não encontrado.");
        }
    });
  • Thank you adventistaam! It worked perfectly.

Browser other questions tagged

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