在我的 angularJS 应用程序中,我有一个递增 x 次的循环。我在循环中使用嵌套的 HTTP get 请求来获取每次迭代的 API 响应。
问题在于 HTTP get 函数中的循环计数器未获取正确的增量值。
// split multiple words
var split = ['stack', 'over'];
// for each word
for(var w = 0; w < split.length; w++) {
// API URL
var api_url = "URL" + split[w]; // correct iteration value, 0, 1, 2, etc...
// get data from API
$http.get(api_url)
// handle successful
.success(function (response) {
console.log(w); // logs 2 everytime! Instead of 0, 1, 2, etc...
});
}
关于如何解决这个问题有什么想法吗?
最佳答案
您的$http.get()
是异步的。您的 for
循环不会等待异步调用完成。因此,您的 for
循环运行至完成,启动所有 ajax 调用,然后稍后您的 $http.get()
调用完成并触发 .success
处理程序。因此,当每个 $http.get()
调用完成时,循环索引位于其结束值。并且,循环索引的结束值为 2
。
您可以通过将 $http.get()
放入函数并将循环索引传递到该函数中来修复它。这个内部函数(通常称为立即调用函数 Express IIFE)单独跟踪每次 ajax 调用的循环索引,因此每个函数都有自己的索引:
// split multiple words
var split = ['stack', 'over'];
// for each word
for (var w = 0; w < split.length; w++) {
(function (i) {
// API URL
var api_url = "URL" + split[i];
// get data from API
$http.get(api_url)
// handle successful
.success(function (response) {
console.log(i); // logs the index that belongs with this ajax call
});
})(w);
}
附注我不清楚 word_index
是什么,因为您没有定义它?这应该是循环索引吗?
请注意,w
是 for
循环中使用的变量。它作为参数传递到新添加的内部函数中,我特意给它起了一个不同的名称:i
。因此,w
被传递到函数中,函数参数将变量命名为 i
。
关于javascript - 嵌套 HTTP Get 中的增量值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33510135/