【问题标题】:each wait until finish $.ajax , and then continue每次等到完成 $.ajax ,然后继续
【发布时间】:2012-01-29 06:05:53
【问题描述】:
    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,因为它具有最后一个值,对不起我的英语,谢谢! !!

【问题讨论】:

标签: jquery ajax each


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    选项 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);
              }
           }
      });
      

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-04-26
          • 2015-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-21
          • 1970-01-01
          • 2018-04-25
          相关资源
          最近更新 更多