简体   繁体   English

如何使用多个 XMLHttpRequest?

[英]How to use multiple XMLHttpRequest?

I need to get 8 JSON from 8 different URL.我需要从 8 个不同的 URL 获取 8 个 JSON。 I stored the query string that I have to change in an Array and I loop through it with a for loop.我将必须更改的查询字符串存储在一个数组中,并使用 for 循环遍历它。 Here is my code:这是我的代码:

var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

var request = new XMLHttpRequest();

for (var i = 0; i < index.length; i++) {

    var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i];

    request.open("GET", url);
    request.onload = function() {
        var data = JSON.parse(request.responseText);
        console.log(data);
    }
    request.send();
}

So far I just want to display each JSON on the console.到目前为止,我只想在控制台上显示每个 JSON。 I don't get any error but I can display only the last JSON with the last index item (noobs2ninjas).我没有收到任何错误,但我只能显示带有最后一个索引项 (noobs2ninjas) 的最后一个 JSON。

Could anybody explain me why?有人可以解释我为什么吗? how do I get the all JSON that I need?我如何获得我需要的所有 JSON?

Thanks谢谢

Could anybody explain me why? 谁能解释一下为什么? how do I get the all JSON that I need? 我如何获得我需要的所有JSON?

In order to send a second request you need to wait for the first to finish. 要发送第二个请求,您需要等待第一个请求完成。 Hence, if you are interested to get the responses in the array order you can loop on each array element and only when you get the response you can loop on the remaining elements: 因此,如果您有兴趣以数组顺序获取响应,则可以在每个数组元素上循环,并且只有在获得响应时,您才可以循环其余元素:

 var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; var request = new XMLHttpRequest(); (function loop(i, length) { if (i>= length) { return; } var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i]; request.open("GET", url); request.onreadystatechange = function() { if(request.readyState === XMLHttpRequest.DONE && request.status === 200) { var data = JSON.parse(request.responseText); console.log('-->' + i + ' id: ' + data._id); loop(i + 1, length); } } request.send(); })(0, index.length); 

Instead, if you want to execute all the request completely asynchronous (in a concurrent way), the request variable must be declared and scoped inside the loop. 相反,如果要完全异步(以并发方式)执行所有请求,则必须在循环内声明和限定请求变量。 One request for each array element. 每个数组元素一个请求 You have some possibilities like: 你有一些可能性:

 var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; for (var i = 0; i < index.length; i++) { var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i]; let request = new XMLHttpRequest(); request.open("GET", url); request.onreadystatechange = function() { if(request.readyState === XMLHttpRequest.DONE && request.status === 200) { var data = JSON.parse(request.responseText); console.log('-->' + data._id); } } request.send(); } 

As per @Wavesailor comment, in order to make a math computation at the end of calls: 根据@Wavesailor评论,为了在调用结束时进行数学计算:

 var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; var request = new XMLHttpRequest(); (function loop(i, length, resultArr) { if (i>= length) { console.log('Finished: ---->' + JSON.stringify(resultArr)); return; } var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i]; request.open("GET", url); request.onreadystatechange = function() { if(request.readyState === XMLHttpRequest.DONE && request.status === 200) { var data = JSON.parse(request.responseText); console.log('-->' + i + ' id: ' + data._id); resultArr.push(data._id); loop(i + 1, length, resultArr); } } request.send(); })(0, index.length, []); 

The problem is that you declare 问题是你申报了

var request = new XMLHttpRequest();

outside of the for loop. for循环之外。 So you instance only one request. 所以你只实例一个请求。

You have to include it inside the for loop. 你必须将它包含在for循环中。

Also, don't forget that ajax is executed asynchronous so you will get the results in a random order. 另外,不要忘记ajax异步执行的,因此您将以随机顺序获取结果。

The value of i variable must be declared using let keyword in order to declare a block scope local variable. 必须使用let关键字声明i变量的值,以声明块范围局部变量。

let allows you to declare variables that are limited in scope to the block . let允许您声明范围受限于块的变量。

let is always used as a solution for closures . let总是用作闭包的解决方案。

Also, you can use an array where you can store the XMLHttpRequest . 此外,您可以使用可以存储XMLHttpRequestarray

 var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"]; requests=new Array(index.length); for (let i = 0; i < index.length; i++) { var url = "https://wind-bow.glitch.me/twitch-api/channels/" + index[i]; requests[i] = new XMLHttpRequest(); requests[i].open("GET", url); requests[i].onload = function() { var data = JSON.parse(requests[i].responseText); console.log(data); } requests[i].send(); } 

You may also prefer to use the Fetch API in the place of XMLHttpRequest . 您可能也更喜欢使用Fetch API代替XMLHttpRequest Then all you have to do is to utilize a few Promise.all() functions. 然后你要做的就是利用一些Promise.all()函数。

 var index = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"], url = "https://wind-bow.glitch.me/twitch-api/channels/", proms = index.map(d => fetch(url+d)); Promise.all(proms) .then(ps => Promise.all(ps.map(p => p.json()))) // p.json() also returns a promise .then(js => js.forEach((j,i) => (console.log(`RESPONSE FOR: ${index[i]}:`), console.log(j)))); 
 .as-console-wrapper { max-height: 100% !important; } 

I just had the same issue. 我刚才有同样的问题。 Just use "this.responseText" instead of "request.responseText". 只需使用“this.responseText”而不是“request.responseText”。 That's it. 而已。

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

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