Perform multiple GET with Xmlhttprequest

Asked

Viewed 179 times

2

how do I get Xmlhttprequest to send multiple requests using a list with pure js, example:

I have the following list of names

Fernando
Lucas

I want to take this list and post one name at a time and display the reply of the request, until all items are finished.

Thanks for the help !

  • And each name should be a separate ajax right? Where do you want to show these results? do you want to show as they come or all together.

  • Each name will be a separate request, I want to show in a simple Alert for now and go showing as they come, thanks so much for the help ;)

  • But requests get or post ? In the title is one thing but then in the middle of the question is another

2 answers

3


For what you want the ideal will be 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 is important to remember that the order in which you receive the answers will not necessarily be the order in which you sent them!

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

Browser other questions tagged

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