问题描述
我是ajax和JavaScript的新手。
我要做的是多次调用ajax函数从资源中获取某些数据,然后将所有数据推到一个数组中,以便稍后在代码中使用它。这是我的代码。
I'm new to ajax and JavaScript.What am trying to do is to call an ajax function several times to fetch certain data from a resource and then "push" all of the data into an array so that I can use it later on in the code. Here is my code.
var arr = [];
var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for (i = 0; i < users.length; i++) {
$.ajax({
url: "https://api.twitch.tv/kraken/streams/" + users[i],
success: function(data) {
arr.push(data);
},
error: function(data) {
arr.push("blank");
},
complete: function() {
if (i == users.length) {
console.log(arr); //This seem to print even when the condition isn't true
}
}
});
}
代码的问题在于,它即使在 i
不等于 users.length
The problem with the code is that, it prints to the console even when i
isn't equal to users.length
我的问题是;在打印到控制台之前,如何确保等到 i == users.length
为真?
请记住,我仍然希望这个过程是异步的。
My question is; how do I make certain that it waits until i == users.length
is true before it prints to the console?Please keep in mind that I still desire the process to be asynchronous.
推荐答案
以下是你如何打电话给所有人请求考虑他们的成功,而不是对另一个人提出请求:
Here is how you can call all requests considering their success without running an request over another:
var arr = [];
var users = ["brunofin", "comster404", "ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
var runRequests = function(userIndex) {
if (users.length == userIndex) {
console.log("runRequests Success", arr);
return;
}
var user = users[userIndex];
$.ajax({
url: "https://api.twitch.tv/kraken/streams/" + user,
success: function(data) {
arr.push(data);
},
error: function() {
arr.push({});
console.error("runRequests Error", "user", arguments);
},
complete: function() {
runRequests(++userIndex);
}
});
};
runRequests(0);
这篇关于如何在for循环中调用ajax函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!