简体   繁体   English

如何通过XMLHttp Get请求传递数组?

[英]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. 我有一个数组,希望在GET请求中使用其中的每个值。 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. 我仍然为test[i]保持不确定状态,而且我不确定这是否是如何通过httpRequest正确传递数组的方法。 I will appreciate any help with this. 我将不胜感激。

The way you are doing it you would have to create a for loop like this: 您这样做的方式必须创建一个如下的for循环:

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. 否则,您可以更改您的API以处理取值数组并返回它们的数据。

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 : 由于未传递参数i ,而您却希望它作为IIFE的参数,所以您对test[i] undefined变得undefined

 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 如果要多个调用,可能需要在循环内发送请求httpRequest.send()

  2. onreadystatechange should define a function ; onreadystatechange应该定义一个function assigning an array doesn't make sense 分配数组没有意义

  3. For simultaneous calls, you might have to create multiple XMLHttpRequest request. 对于同时进行的调用,您可能必须创建多个XMLHttpRequest请求。 Right now you are only creating one and changing the url, these will just get aborted. 现在,您只创建一个并更改URL,这些将被终止。

Checkout more detailed answer here. 在此处结帐更详细的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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