繁体   English   中英

jQuery:如何在ajax调用完成后回调每个循环?

[英]JQuery: How to callback each loop after completion of ajax call?

Ajax调用完成后如何回调每个循环。

请找到我的代码如下。

故事:

让我们假设我有3个值X,Y,Z。 首先,我获取X值,发送给django视图及其使用请求模块以获取一些信息,并推送至div类push_new_info_here ,在下一个迭代中,我必须获取Y值。 怎么做 ? 请注意:先前的ajax调用应该成功。

最后一句话:我正在收集(X,Y,Z)的所有信息,然后使用python合并并推送到div类push_new_info_here

window.onload = function() {

  $.each(["X","Y","Z"], function( index, value ) {

      $.post('/find/'+value+'/',{},function(data){
          $('.push_new_info_here').empty();
          $('.push_new_info_here').html(data);
      });

  });

};

这样-如果您想查看数据或将超时时间更改为足够长的时间以使用户能够看到,请使用.append:

var arr = ["X","Y","Z"],cnt=0;

function postIt() {
  if (cnt >= arr.length) return; // stop
  $.post('/find/'+arr[cnt]+'/',{},function(data){
      $('.push_new_info_here').empty().html(data); // or .append
      cnt++; 
      postIt(); // or setTimeout(postIt,3000); // give server a breather
  });
}


$(function() {
  postIt();
});

尝试将调用包装到函数中,然后使用AJAX .done方法遍历数组。 例如

window.onload = function() {
  recursiveAjax(["X","Y","Z"])
};

function recursiveAjax(values){
  //basic error testing
  if (typeof values == "undefined" || values.length == 0) return false
  var value = values.pop();
  $.post('/find/'+value+'/',{},function(data){
    $('.push_new_info_here').empty();
    $('.push_new_info_here').html(data);
    recursiveAjax(values)
  });
}'

编辑:为避免破坏数组,我们可以将克隆的副本发送到该函数。 例如:

window.onload = function() {
  var tempArray = ["X","Y","Z"]
  recursiveAjax(tempArray.slice())
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM