jQuery AJAX 调用 for 循环 [英] jQuery AJAX calls in for loop
问题描述
我是使用 AJAX 的新手,我正在编写一个用户脚本,它将处理页面上的一堆链接并为每个链接进行 AJAX 调用.
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.
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');
}
});
}
简单地说,我有一个包含链接列表的页面.我希望遍历链接并让 AJAX 处理每个链接页面的内容,并报告该页面是否包含指定的内容.
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.
我遇到的问题是用于遍历 linkList 的 [i] 的值始终为 6,而且永远不应该如此.我假设我需要传递一些数据,以便当 .done 最终触发时,它知道 AJAX 首次触发时的 [i] 值,而不是 .done 稍后触发时的 [i] 值.
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.
我如何确保 .done 在第一次调用 AJAX 时知道它的 [i] 值?
How do I go about ensuring .done knows it's [i] value when AJAX is first called?
推荐答案
最简单的方法是使用闭包.每当你在循环中有一些异步的东西时,都是一样的.
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);
}
}
在这个伪代码片段中,内部函数捕获了i
引用的存储位置.循环运行,i
递增到其最终值,然后开始调用异步回调,所有这些回调都查找完全相同的位置(不是值).
In this pseudocode snippet, the inner function captures the storage location referenced 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).
一般的解决方案是这样的:
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.
这里,外部 i
的 value 被传递到包装自执行匿名函数中;这个唯一值的位置被异步回调捕获.这样,每个 async 都有自己的值,在调用自执行函数时确定.
Here, the value of 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.
这篇关于jQuery AJAX 调用 for 循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!