jQuery AJAX 调用 for 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21819905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery AJAX calls in for loop
提问by Edge
I'm new to using AJAX, and I'm writing a userscript that will process a bunch of links on a page and make AJAX calls for each one.
我是使用 AJAX 的新手,我正在编写一个用户脚本,它将处理页面上的一堆链接并为每个链接进行 AJAX 调用。
for (var i = 0; i < linkList.length; i++)
{
$.ajax({
url: linkList[i].getAttribute("href"),
cache: false
}).done(function( html )
{
var hasAppended = false;
if (html.indexOf('someStringOnGottenPage') != -1 && !hasAppended)
{
hasAppended = true;
var id = linkList[i].getAttribute("href").substring(linkList[i].getAttribute("href").indexOf('='));
$( "#links a[href*='" + id + "']" ).append(' THIS PAGE CONTAINS SPECIFIED DATA');
}
});
}
To try to put it simply, I have a page with a list of links. I wish to iterate through the links and get AJAX to process the contents of each of the links pages, and report back if that page contains something specified.
简单地说,我有一个包含链接列表的页面。我希望遍历链接并让 AJAX 处理每个链接页面的内容,并报告该页面是否包含指定的内容。
The issue I'm having is the value of [i] used to iterate through the linkList is always 6, and it should never be. I'm assuming I need to pass some data so that when .done finally triggers, it knows its [i] value from when AJAX first triggered and not the value of [i] when .done triggers later.
我遇到的问题是用于遍历 linkList 的 [i] 的值始终为 6,而且永远不应该如此。我假设我需要传递一些数据,以便当 .done 最终触发时,它知道 AJAX 首次触发时的 [i] 值,而不是 .done 稍后触发时的 [i] 值。
How do I go about ensuring .done knows it's [i] value when AJAX is first called?
我如何确保 .done 在第一次调用 AJAX 时知道它的 [i] 值?
回答by Amadan
The easiest way is to use a closure. Whenever you have something asynchronous in a loop, it is the same thing.
最简单的方法是使用闭包。每当您在循环中有一些异步的东西时,它都是一样的。
for (var i .....) {
asynchronousFunction(function() {
use(i);
}
}
In this pseudocode snippet, the inner function captures the storage locationreferenced by i
. The loop runs, the i
increments to its final value, and then the async callbacks start getting called, all of them looking up the exact same location(not value).
在这个伪代码片段中,内部函数捕获了引用的存储位置i
。循环运行,i
递增到其最终值,然后开始调用异步回调,所有这些都查找完全相同的位置(不是值)。
The general solution is this:
一般的解决办法是这样的:
for (var i .....) {
(function (i) {
asynchronousFunction(function() {
use(i);
});
})(i);
}
i.e. wrap the whole contents of your loop in an self-executing function.
即将循环的全部内容包装在一个自执行函数中。
Here, the valueof outer i
gets passed into the wrapping self-executing anonymous function; this unique value's location gets captured by the async callback. In this way, each async gets its own value, determined at the moment the self-executing function is invoked.
在这里,outer的值i
被传递到包装的自执行匿名函数中;这个唯一值的位置被异步回调捕获。通过这种方式,每个 async 都有自己的值,在调用自执行函数时确定。
回答by Arun P Johny
The links in the comment section of the question tells you what is wrong in your code... but you can have a better solution than the once explained there.
问题评论部分中的链接会告诉您代码中有什么问题……但是您可以拥有比曾经在那里解释过的更好的解决方案。
Try $.each()to iterate through the list(assuming it is an array), so that the callback passed will create a separate closure for each iteration
尝试$.each()遍历列表(假设它是一个数组),以便传递的回调将为每次迭代创建一个单独的闭包
$.each(linkList, function (i, item) {
$.ajax({
url: item.getAttribute("href"),
cache: false
}).done(function (html) {
var hasAppended = false;
if (html.indexOf('someStringOnGottenPage') != -1 && !hasAppended) {
hasAppended = true;
var id = item.getAttribute("href").substring(item.getAttribute("href").indexOf('='));
$("#links a[href*='" + id + "']").append(' THIS PAGE CONTAINS SPECIFIED DATA');
}
});
})
If it is an jQuery object then use .each()
如果它是一个 jQuery 对象,则使用.each()
linkList.each(function (i, item) {
var $item = $(item),
href = $item.attr("href");
$.ajax({
url: href,
cache: false
}).done(function (html) {
var hasAppended = false;
if (html.indexOf('someStringOnGottenPage') != -1 && !hasAppended) {
hasAppended = true;
var id = href.substring(href.indexOf('='));
$("#links a[href*='" + id + "']").append(' THIS PAGE CONTAINS SPECIFIED DATA');
}
});
})