Searching for data via ajax

Asked

Viewed 323 times

0

I have an API running local with the address http://localhost:8080/core-web/Rest/usuarios/79. The number 79 at the end is the user id.

This API which is in JAVA returns me the following data:

{
    "id": 79,
    "nome": "Francis",
    "sobrenome": "",
    "sexo": "M",
    "email": "[email protected]",
    "senha": "8D969EEF6ECAD3C29A3A629280E686CF0C3F5D5A86AFF3CA12020C923ADC6C92",
    "cpf": "035.699.346-21",
    "perfil": null,
    "cep": "35162-000",
    "rua": "Vila Celeste",
    "bairro": "Vila Celeste",
    "cidade": "Ipatinga",
    "estado": "mg",
    "dataNascimento": "1980-10-23",
    "grauEscolaridade": null,
    "telefone": null,
    "celular": null,
    "quantidadeConvite": null,
    "imagem": null
}

This is my GET function:

function get(url) {

  return new Promise((resolve, reject) => {

  let xhr = new XMLHttpRequest();

  xhr.open("GET", url);
  xhr.onreadystatechange = () => {

    if(xhr.readyState == 4) {
      if(xhr.status == 200) {
      resolve(JSON.parse(xhr.responseText));
      } else {
        reject(xhr.responseText);
      }
    }
  };

  xhr.send();
  });
}

then when I call this function by passing the type get address('http://localhost:8080/core-web/Rest/usuarios/79'); it shows in the.log console the data as above.

So I want to filter the data and select only the name or any other data to fill for example an H1 tag in my view. How can I do that?

  • Does the resulting json have a list of users or a single user ? I advise you to put in an example json so that it is clear how to treat it, as well as the javascript code with ajax you are using to get json

1 answer

2


You need to create a Object with the JSON that was returned from the request and access it with the following syntax User.nome as in this example and then insert into the tag you want, either by ID or Class, in case I used the innerHTML javascript.

var User = {
    "id": 79,
    "nome": "Francis",
    "sobrenome": "",
    "sexo": "M",
    "email": "[email protected]",
    "senha": "8D969EEF6ECAD3C29A3A629280E686CF0C3F5D5A86AFF3CA12020C923ADC6C92",
    "cpf": "035.699.346-21",
    "perfil": null,
    "cep": "35162-000",
    "rua": "Vila Celeste",
    "bairro": "Vila Celeste",
    "cidade": "Ipatinga",
    "estado": "mg",
    "dataNascimento": "1980-10-23",
    "grauEscolaridade": null,
    "telefone": null,
    "celular": null,
    "quantidadeConvite": null,
    "imagem": null
}

document.getElementById("nome").innerHTML = User.nome;
<h1 id="nome"> </h1>

Browser other questions tagged

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