How to set variables with JSON received from an AJAX request

Asked

Viewed 80 times

0

I am receiving a JSON and would like to set variables with such information. How do I do this?

inserir a descrição da imagem aqui

$.ajax({
    url: "/pessoa-gerenciar/consultar-codigo-postal",
    type: "GET",
    data: { codigoPostal: $('#PessoasEnderecosViewModel_' + rowIndice + '__CodigoPostal').val().replace("-", ""), paisId: $('#PessoasEnderecosViewModel_' + rowIndice + '__PaisId').val() },
    traditional: true,
    success: function (data) {
        var dados = JSON.stringify(data);

        var codigo = ?
        var logradouro = 



    },
    error: function () {
        alert("Oops! Algo deu errado.");
    }
});
  • do not need to stringfy, the data is already a json object, just a date.algumacoisa for example data.cep

  • Ah ok.. Only that the data returns as if it were a class. It has the name cep and inside the Fields... How I get their information?

1 answer

0


JSON.stringify serves to transform an object into a string with JSON format, is exactly the opposite of what you want.

If in the answer of your server is sent the Content-Type of response, data automatically will be an object, but in doubt, to ensure you can add the property dataType in your AJAX to interpret the answer as a JSON and parse it for object automatically.

So just access the properties of this object:

$.ajax({
    url: "/pessoa-gerenciar/consultar-codigo-postal",
    type: "GET",
    dataType: "JSON",
    data: { codigoPostal: $('#PessoasEnderecosViewModel_' + rowIndice + '__CodigoPostal').val().replace("-", ""), paisId: $('#PessoasEnderecosViewModel_' + rowIndice + '__PaisId').val() },
    traditional: true,
    success: function (data) {

        var codigo = data.cep.codigo;
        var logradouro = data.cep.logadouro;



    },
    error: function () {
        alert("Oops! Algo deu errado.");
    }
});
  • Thanks @user140828!!!

Browser other questions tagged

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