每个等待,直到完成$.ajax,然后继续。

问题描述 投票:8回答:4
    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变种,因为它有最后的值,对不起,我的英语,THANK YOU!!!!!!!。

jquery ajax each
4个回答
18
投票

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

选项2:同步进行ajax请求。

  • global:

     $.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);
            }
         }
    });
    

0
投票

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


0
投票

在你的 $.ajax 呼叫 async: false 它将发送一个阻止请求。


0
投票

设置 async 变成假的 $.ajax 呼叫。

© www.soinside.com 2019 - 2024. All rights reserved.