简体   繁体   中英

How to pass an array through an XMLHttp Get request?

I have an array that I want to using each value from it in my GET request. Something like this :

function something(){
    let test = ['something', 'other', 'test'];
    let httpRequest;
     function makeRequest(){
      httpRequest = new XMLHttpRequest;
      httpRequest.onreadystatechange = test;
      for(var i = 0; i < test.length; i++){
      (function(i){
      httpRequest.open('GET', 'https://test.com/' + test[i] , true);
      })()}
      httpeRequest.send();
   }
}

I keep getting undefined for test[i] though, and I'm not sure if this is how to correctly pass arrays through an httpRequest either. I will appreciate any help with this.

The way you are doing it you would have to create a for loop like this:

for(var i = 0; i < test.length; i++){    
    makeRequest(test[i])

You have to create a new request for each item. Otherwise you could change your API to handle taking in an array of values and returning the data for them.

You are getting undefined for test[i] because you are not passing the parameter i , whereas you are expecting it as an argument in the IIFE :

 function something() { let test = ['something', 'other', 'test']; let httpRequest; function makeRequest() { httpRequest = new XMLHttpRequest; httpRequest.onreadystatechange = test; for (var i = 0; i < test.length; i++) { (function(i) { console.log(test[i]); httpRequest.open('GET', 'https://test.com/' + test[i], true); httpRequest.send(); // send request within loop })(i); // pass i here } // httpRequest.send(); } makeRequest(); // call for testing } something(); // call for testing 

Other thing, there are some flaws in the code, like:

  1. You might need to send the request httpRequest.send() within the loop if you want multiple calls

  2. onreadystatechange should define a function ; assigning an array doesn't make sense

  3. For simultaneous calls, you might have to create multiple XMLHttpRequest request. Right now you are only creating one and changing the url, these will just get aborted.

Checkout more detailed answer here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM