每个人等到完成$ .ajax,然后继续

function genTask(elem){ elem.each(function(){ $this=$(this).parent('.cntTasks'); var pattern=/taskId-(.*)$/ var idTask=$this.attr('id').match(pattern); var data='id_task='+idTask[1]; if(typeof jsVar2 !='undefined') data+=jsVar2; $.ajax({ type: "POST", url: domain+"/view_tasks/gen_tasks/", dataType: 'html', data: data, success: function(dt){ $this.find('.contChildTasks').html(dt); childs=$this.children('.taskDesc').find('.has_child'); if(childs.length!=0) genTask(childs); } } }); $this.find('.taskDesc').show(); }); } if(typeof jsVar2 !='undefined') genTask($('.cntTasks .has_child')); }); 

怎么可能让$.each等到动作$.ajax完成,然后继续循环,我不能得到$ this var,因为它有最后一个值,对不起我的英语,谢谢!

选项1:在success处理程序中切换到数组中的下一个元素。

选项2:同步发出ajax请求:

  • 全球:

      $.ajaxSetup({ async: false }); 
  • 或直接在请求中:

      $.ajax({ async: false, type: "POST", url: domain+"/view_tasks/gen_tasks/", dataType: 'html', data: data, success: function(dt){ $this.find('.contChildTasks').html(dt); childs=$this.children('.taskDesc').find('.has_child'); if(childs.length!=0) genTask(childs); } } }); 

尝试把ajaxsetup({asynch:false}); 在你的每个循环之前,然后在循环之后将其重置为true,这样你未来的ajax请求仍然可以是asych

$.ajax调用中添加async: false ,它将发送阻止请求。

$.ajax调用上将async设置为false。