Searching for data via ajax

0

I have an API running local with the link address. The number 79 at the end is the id of the user.

This API that 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 passing the address type get (' link '); it shows in the console.log 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 this?

    
asked by anonymous 02.08.2017 / 01:52

1 answer

0

You need to create a Object with the returned JSON of the request and access it with the following syntax User.nome as in this example and then insert in the tag that you want, either by ID or Class, in this case I used the innerHTML of 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>
    
02.08.2017 / 20:06