Extract arrays and JSON objects returned with jQuery

3

I'm making a request in a Web Service using jQuery this way:

var dados = jQuery( this ).serialize();

jQuery.ajax({
     type: "POST",
     url: "http://meusite.com/test",
     data: dados,
     success: function( data )
     {
         // quero exibir os dados que estão dentro de data
      }
});

The return JSON is exactly this when the user's login is WRONG.

{
    "error": true,
    "message": "Login failed. Incorrect credentials"
}

If the authentication is CORRECT, the result is this:

{
    "error": false,
    "user": [
        {
            "id": 2,
            "fullname": "Romero Brito",
            "email": "[email protected]",
            "created_at": "2017-01-20 01:03:48"
        }
    ]
}

How do I extract arrays and JSON objects returned with jQuery? How do I display the message that is inside message and those through data ?

EDIT

At first it can be listed the data simply in a alert() or even only in console.log() .

    
asked by anonymous 20.01.2017 / 06:21

2 answers

1

Good evening,

If you specify in the option object sent to method .ajax to key dataType , you inform what type of data you are expecting from the server. In your case, it would look something like this:

jQuery.ajax({
     /* ... */
     dataType: 'json',
     /*... */
})

However , as default, jQuery tries to guess - Intelligent Guess -, the format of the received data (xml, script , json ...) from the server response. So this above parameter would only need to be informed if jQuery could not understand that the response is a JSON (usually due to a badly formatted message by the server), or you want to make sure the result is always the one (in this case , if jQuery can not parse, it will invoke the callback error ).

That said, then your callback function success will be invoked with the first parameter containing the formatted data parsed ) (in your case, an object JavaScript). And you can manipulate it as if you were manipulating a JavaScript object normally. Something like this:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
     {
         /* seu dado já deve estar no parâmetro data */
         console.log("Login com sucesso? ", !data.error);
         if (!data.error) {
            var user = data.user[0]; //seu user é um array, então pego o primeiro elemento dessa array, por exemplo
            console.log("Nome completo do usuário: ", user.fullname);
         }
     }
});

The above code is for debug purposes only, because it will write to the browser console.

I do not know if this was your question (on how to manipulate the data received).

If you want to display a simple message, you can call the alert . This will show a dialog box with the (very simple) message.

Or, if you want to insert this message into the body of the page in some way, or make element interactions, this involves manipulations in the DOM, and can be easily done by jQuery . A very simple example:

jQuery.ajax({
    /* ... */ 
    success: function(data, textStatus, jqXHR )
    {
        var textMessage;
        if (data.error) {
            textMessage = "Ocorreu um erro ao relizar o login: " + data.message;
        } else {
            textMessage = "Login realizado com sucesso! Bem vindo, " + data.user[0].fullname + "!";
        }
        $("body").append( $("<p></p>", { text: textMessage }) );
    }
});

The above example only adds to <body> a <p> (paragraph) with a message.

    
20.01.2017 / 06:45
1
Using dataType as json you can get the return in that format to iterate through the keys or values.

jQuery.ajax({
  type: "GET",
  url: "https://raw.githubusercontent.com/luccascosta/library/master/js/ret.json",
  dataType: "json",
  success: function(data) {
    console.log(data);
    console.log(data['message']);
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Fortheuserreturn

jQuery.ajax({
  type: "GET",
  url: "https://raw.githubusercontent.com/luccascosta/library/master/js/user.json",
  dataType: "json",
  success: function(data) {
    console.log(data);
    console.log(data.user[0].fullname); // user[0] é para acessar o index zero do array de user. Dessa forma é possível acessar qualquer propriedade do objeto dentro desse array
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

PS: In the example is method get only to illustrate the return.

    
20.01.2017 / 13:29