Show data dynamically

Asked

Viewed 29 times

1

I have this ajax that requests a list of names for me.. this is the code in pure javascript:

 function listagem() {

 var lista = {

idUsuario: document.querySelector(".campo").value,
token: document.querySelector(".campo-token").value
};

let xhr = new XMLHttpRequest();
var variavel = document.querySelector(".token-servico").innerHTML;
xhr.open("POST", "http://listAll", true);
xhr.setRequestHeader("Content-type", "application/json");
xhr.setRequestHeader("Authorization", "Bearer " + variavel);

xhr.addEventListener("load", function () {



  if (xhr.status == 200) {

    window.sessionStorage.setItem('lista', xhr.responseText);

    var lista = window.sessionStorage.getItem('lista');

    lista = JSON.parse(lista);

    let x = document.querySelector('#body')

    lista.map(item => {

      x.innerHTML += '<tr><td>'+ item.nome +'</td></tr>'
    });

}

However, the way the listing looks only appears after I click a button. What can I do to make the list appear as soon as the page is accessed?

Grateful to those who answer

  • 1

    That’s all: window.onload = listagem;

1 answer

1


Change the function listagem() for document.addEventListener("DOMContentLoaded", function(event){, which will execute the code when the page is loaded:

Not to mention that there are snippets in your code without closure that I fixed below:

document.addEventListener("DOMContentLoaded", function(){

   var lista = {

      idUsuario: document.querySelector(".campo").value,
      token: document.querySelector(".campo-token").value
   };

   let xhr = new XMLHttpRequest();
   var variavel = document.querySelector(".token-servico").innerHTML;
   xhr.open("POST", "http://listAll", true);
   xhr.setRequestHeader("Content-type", "application/json");
   xhr.setRequestHeader("Authorization", "Bearer " + variavel);

   xhr.addEventListener("load", function () {

      if (xhr.status == 200) {

         window.sessionStorage.setItem('lista', xhr.responseText);

         var lista = window.sessionStorage.getItem('lista');

         lista = JSON.parse(lista);

         let x = document.querySelector('#body')

         lista.map(item => {

            x.innerHTML += '<tr><td>'+ item.nome +'</td></tr>'
         });
      }
   });

});

Browser other questions tagged

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