Show data dynamically

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 is listed appears only after I click a button. What can I do to make the list appear as soon as the page is accessed?

Thanks to who responds

    
asked by anonymous 09.02.2018 / 21:51

1 answer

1

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

Not to mention that there are excerpts in your unclosed code that I've corrected 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>'
         });
      }
   });

});
    
09.02.2018 / 22:39