如果ajax完成,转到下一个迭代$ .each?

时间:2013-04-24 16:33:56

标签: javascript ajax jquery each

请参阅下面的代码,它似乎执行了许多$.post而不等待data == "1"

如果$.each等于data,则应该进行下一次迭代(1)。

怎么做?

$.each(data, function(index) {
  $.post("tracking.php",  { action: "send", id: getId }, function(data) {
    if (data == "1") {
      //
    }
  },'json');
});

3 个答案:

答案 0 :(得分:2)

由于$.post是异步的,因此您无法使用它来控制循环。您可以使用以下结构:

var data = [1, 2, 3];

function iterator(arr) {
    function iterate(i) {
        // Use `arr[i]`
        $.post("tracking.php",  { action: "send", id: getId }, function(data) {
            if (data == "1") {
                iterate(++i);
            }
        }, "json");
    }
    iterate(0);
}

iterator(data);

DEMO: http://jsfiddle.net/Ezwj4/

当然,在演示中,我必须修改代码/参数以使其与jsFiddle一起使用。注意它在响应不是"1"之后是如何停止的(这只是数组中的值,因为我只需要回显该值以显示它是如何工作的)。您可以观看浏览器的控制台,看看发生了什么。

<强>更新

为确保不超过数组的边界,您需要检查其长度。这是一个更新:

function iterator(arr) {
    // You can use `arr` anywhere inside of `iterator`
    function iterate(i) {
        // You can use `i` anywhere inside of `iterate`
        if (i < arr.length) {
            $.post("tracking.php",  { action: "send", id: getId }, function(data) {
                if (data == "1") {
                    iterate(++i);
                }
            }, "json");
        }
    }
    iterate(0);
}

答案 1 :(得分:0)

您可以使用数组post的第一个索引调用第一个data请求,然后等待response(data)返回,然后在下一个索引上触发另一个post请求等等:

function posts(index) {
  $.post("tracking.php",  { action: "send", id: getId }, function(response) {
    if (response == "1") {
       index++;
       if (index < data.length) post(index); //call the function "post" again only if index is lower than the array "data" length.
       }
    }
  },'json');
});
posts(0);

答案 2 :(得分:-1)

使用$ .each和异步请求无法控制循环的执行,但是,使用for循环可以完成它:

for(var index in data){
    data = 0;
    $.ajax({
        url:"tracking.php",  
        data: { action: "send", id: getId }, 
        type: 'POST',
        async: false,
        success: function(tmpData){
          data = tmpData
        }
    });
    if(data != '1'){
        break;
    }
}

在这个例子中,我们使用for循环和jQuery sync ajax请求从服务器获取结果并验证该值是否是预期的。如果返回不同的“1”,我们只需断开(停止)循环。