Treatment JSON

Asked

Viewed 133 times

0

Through JQUERY, I need to make a request via POST where I’ll get a JSON with a token. The JSON return I get after sending the POST is this:

{
    "Token": "e27bb0a7-e65b-4cc3-a82e-7a2a3c26a248",
    "Codigo": 0
}

My question is: How do I read this token? An analyst told me that I should do something more or less like this:

$(document).ready(function() {

	var settings = {
	  "async": true,
	  "crossDomain": true,
	  "url": "https://siteexemplo.br/login/geraTok",
	  "method": "POST",
	  "headers": {
	    "content-type": "application/json",
	  },
	  "data": {
	    "RA": "12345",
	    "senha": "xxx"
	  }
	}
	 
	$.ajax(settings).done(function (response) {
	  console.log(response);
	});

});

But after that? Where’s the token? How to pass it to a variable for example?

Personal thank you!

2 answers

2


{ "Token": "e27bb0a7-e65b-4cc3-a82e-7a2a3c26a248", "Codigo": 0 } é a resposta do servidor em `JSON`.

response takes this answer in object form, so just store it...

$.ajax(settings).done(function (response) {
          var token = response.Token;
          console.log(token);
        });

0

The return of the data appeared in the variable response which is the function parameter when it finishes (done), you can simply use the notation of ponto to access the keys of a json, see:

$.ajax(settings).done(function (response) {
  console.log(response.Token); // pega o token retornado do json
  console.log(response.Codigo); // pega o código retornado do json
});
  • speaks @Rafael Acioly, I believe that accessing the keys of a JSON would not be a correct term, JSON is for transfer only, when interpreted by javascript can already be treated as object, vlw!

Browser other questions tagged

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