I can not retrieve JSON in jQuery

0

I can not display 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) , JSON appears complete.

What am I doing wrong?

    
asked by anonymous 27.08.2017 / 22:40

3 answers

0

You may have to do parse of json:

$.post("<?php echo site_url('Welcome/viacep'); ?>", {cep: cep}, 
    function(response){ 
        var dados = JSON.parse(response);
        alert(dados.uf);
    }
, 'json' );
    
27.08.2017 / 22:45
0

Try this:

$.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.");
        }
    });
    
27.08.2017 / 22:55
0

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

let obj = JSON.parse(dados);

Handling you use obj instead of dados .

alert(obj.cep);

jQuery also has a function to deserialize JSON, $.parseJSON , but it is considered obsolete, so you can use 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. Font

    
27.08.2017 / 22:53