如何在for循环中运行ajax后调用函数

时间:2012-12-26 04:45:53

标签: javascript jquery ajax

  

可能重复:
  Multiple ajax calls inside a each() function.. then do something once ALL of them are finished?

在for循环中运行ajax后如何执行函数。这里的例子我在循环中运行了这个ajax,

for (var countDevice = 0; countDevice<32; countDevice++){
  var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
  $.ajax({
    type: "POST",
    url: "CalculateTable",
    data: dataString,
    dataType: "json", 
    //if received a response from the server
    success: function( device, textStatus, jqXHR) {
     //Do something                                 
    }
  });
}

我想确保只在上面的for循环结束后才运行下面的这个函数。

function drawTable(){
  //Do something
}

任何人都可以提出如何使其成为可能吗?感谢您花时间阅读和回答。

3 个答案:

答案 0 :(得分:2)

如果您想以线性方式运行它,您可以像这样编写代码

var countDevice = 0;
(function CountDeviceLoop() {
  if (countDevice == 32) {
    // you can place draw table here or .....
    // drawTable();
    return;
  }

  var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
  $.ajax({
    type: "POST",
    url: "CalculateTable",
    data: dataString,
    dataType: "json", 
    //if received a response from the server
    success: function( device, textStatus, jqXHR) {
      //Do something


      //after done sth
      countDevice ++;
      CountDeviceLoop();                             
    }
  });
})();

// here
// drawTable();

因为ajax方法是异步的,你可以用这种方式运行你的循环...或者如果你想使用'for loop'来运行你的程序,你可以使用@MadSkunk的代码

答案 1 :(得分:0)

for (var countDevice = 0; countDevice<=32; countDevice++)
{
if (countDevice == 32)
{
drawTable();
}
else {
var dataString="modbus="+(countDevice+1)+"_"+newDate+".xml";
$.ajax({
type: "POST",
url: "CalculateTable",
data: dataString,
dataType: "json",

//if received a response from the server
success: function( device, textStatus, jqXHR) {
//Do something
}
});
}
}

答案 2 :(得分:-1)

Yoo也可以尝试

$('your selector').ajaxComplete(function() {
  drawTable();
});