jQuery的AJAX调用循环 [英] jQuery AJAX calls in for loop

查看:116
本文介绍了jQuery的AJAX调用循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来使用AJAX,和我正在写一个userscript将处理一堆的页面上的链接,并为每一个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.

我遇到的问题是[I]用于遍历该链表的值总是6,它不应该。我假设我需要通过一些数据,这样,当.done终于​​触发,它知道它的[I]从什么时候AJAX首先触发值和[我]不是值时.done后触发。

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是第一个叫价值?

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 .....) {
  async(function() {
    use(i);
  }
}

在此伪code片段中,内部函数捕获的存储地点的由引用的我。循环运行时,递增到它的最终值,然后异步回调开始得到所谓的,所有的人都抬起头来完全一样的位置的(不是值)。

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) {
    async(function() {
      use(i);
    });
  })(i);
}

即。包装在一个自动执行功能的环路的全部内容。

i.e. wrap the whole contents of your loop in an self-executing function.

在这里,的外被传递到包装自执行匿名函数;这种独特的价值位置得到由异步回调抓获。这样一来,每个异步都有自己的价值,在自动执行函数被调用的瞬间决定的。

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调用循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆