让循环等待ajax调用

时间:2014-05-19 14:13:05

标签: javascript

是否有可能让这个循环等到AJAX调用完成后才进入下一次迭代?

for(curr;curr < total;curr++) {
    $this.val('Uploading '+(curr+1)+' out of '+total);
    var tmpStr = JSON.stringify(o[curr]).replace("&", "and");
    tmp[0] = JSON.parse(tmpStr);

    $.ajax({
        type: 'POST',
        url: 'http://example.com/api/post',
        data: "data="+JSON.stringify(tmp),
        success: function(msg) {

            var d = JSON.parse(msg);
            if (d.success) {

                //localStorage.removeItem("data");
            }
            else
            {
                alert("Data failed to upload, please try again");
            }
        },
        error: function(msg) {
            alert("Data failed to upload, please try again");
            $this.val('Upload to CMS');
        }
    });
}

2 个答案:

答案 0 :(得分:2)

您可以将when关键字与递归函数一起使用。 when关键字允许您等待ajax调用。在ajax调用之后,当函数将结果发送到done函数时,即使失败也是如此。您可以通过在ajax调用中添加一些错误控制来扩展您的方案。但我给出了这个例子:

function reCursive(curr,total)
{
    if(curr < total) 
    {
        $this.val('Uploading '+(curr+1)+' out of '+total);
        var tmpStr = JSON.stringify(o[curr]).replace("&", "and");
        tmp[0] = JSON.parse(tmpStr);

        $.when(function() 
        {
            return $.ajax(
            {
                type: 'POST',
                url: 'http://mvc.sivapi.sheffieldnetwork.com/form/submit/submit/meadowhallEaster/',
                data: "data="+JSON.stringify(tmp),
                success: function(msg) 
                {
                    var d = JSON.parse(msg);
                    if (d.success) 
                    {
                        //localStorage.removeItem("data");
                    }
                    else
                    {
                        alert("Data failed to upload, please try again");
                    }
                },
                error: function(msg) 
                {
                    alert("Data failed to upload, please try again");
                    $this.val('Upload to CMS');
                }
            });
        }).done(function (x) 
        {
            //When you get the result from your ajax call. Write your code here.
            curr++;
            reCursive(curr, total);
        });
    }
}

答案 1 :(得分:2)

虽然您无法使循环for循环等待,但您可以重写代码以使用其他样式的调用来运行。

function runOnce(curr) {
  $this.val('Uploading ' + (curr + 1) + ' out of ' + total);
  var tmpStr = JSON.stringify(o[curr]).replace("&", "and");
  tmp[0] = JSON.parse(tmpStr);

  $.ajax({
    type: 'POST',
    url: 'http://mvc.sivapi.sheffieldnetwork.com/form/submit/submit/meadowhallEaster/',
    data: "data=" + JSON.stringify(tmp),

    // ***ADDED HERE*
    always: {
      if (curr < total) {
        runOnce(curr+1);
      } else {
        alert("All done-- you could call your next function from here.");
      }
    },
    success: function (msg) {

      var d = JSON.parse(msg);
      if (d.success) {
        //localStorage.removeItem("data");
      } else {
        alert("Data failed to upload, please try again");
      }
    },
    error: function (msg) {
      alert("Data failed to upload, please try again");
      $this.val('Upload to CMS');
    }
  });
}

// Set things up and run it once.
// The '0' is what the loop index would be.
runOnce(0);