Perform multiple GET with XMLHttpRequest

2

How do I make the XMLHttpRequest send multiple requests using a list with pure js, eg:

I have the following list of names

Fernando
Lucas

I want to pick up this list and do a post with one name at a time and display the response of the request until all the items are finished.

Thanks for the help!

    
asked by anonymous 08.10.2017 / 12:30

2 answers

3

For what you want the ideal is to create an array of names and as you go through it makes ajax requests creating and configuring the objects XMLHttpRequest :

const url = "http://www.a_sua_pagina_aqui.php";
const nomes = ["Fernando","Lucas"];

nomes.forEach((nome) => { //percorrer todos os nomes
  const xhttp = new XMLHttpRequest(); //criar o objeto para o pedido

  xhttp.onreadystatechange = function() {
      //apenas dentro do if tem a resposta à requisição
      if (this.readyState == 4 && this.status == 200) {
         console.log(xhttp.responseText); //resposta vem no responseText
      }
  };

  xhttp.open("POST", url , true); //requisição do tipo POST com true para ser assíncrono
  xhttp.send("nome=" + nome); //parâmetros enviados aqui, neste caso apenas o nome
});

It's important to remember that the order you get the answers will not necessarily be the order you sent them!

    
08.10.2017 / 13:40
3

Simple!

var i = 0;
var user = [
        "Pedro",
        "Jose",
        "Marcos",
        "Lucas"
        ];


 function ajax( get ) {
 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {

 // readyState
 if (this.readyState == 4) {

    if(this.status == 200) {

        // alert('XHTTP LOAD');
        reload(i);
        i++;

    } else {

        alert('ERRO XHTTP');

    }
}
};
 xhttp.open("GET", "nomes.php?user=" + encodeURI( get ) , true); // start
 xhttp.send();
}

function reload(i) {
   if(i >= user.length ) alert('FIM'); else ajax( user[ i ]);
}
reload(i); // start
    
08.10.2017 / 13:42