代码之家  ›  专栏  ›  技术社区  ›  Haim Evgi

jquery:等待所有ajax调用完成,然后继续[duplicate]

  •  14
  • Haim Evgi  · 技术社区  · 15 年前

    我的文档中有一些ajax调用。ready()

    比如:

    for (j=1; j <= 7; j++){
      (function(index) {
        $.getJSON('my.php', {id:index}, 
          function(data) {
             $.each(data, function(index2, array){
             ........
             });  
          });
        })(j)
    } 
    
    //DO NOT CONTINUE UNTIL FINISH AJAX CALLS   
    
     ........
    MORE JQUERY CODE
    

    我怎样才能强迫它等待,而不是继续,直到我们从ajax请求中得到所有的回调?

    5 回复  |  直到 13 年前
        1
  •  16
  •   sandino Martin Deandreis    13 年前

    我根本不喜欢任何答案,最好的方法(因为Jquery 1.5+)是使用延迟对象,这些对象是用来操作异步调用的,您可以解决:

    $.when($.ajax("/page1.php"), $.ajax("/page2.php"))
      .then(myFunc, myFailure);
    

    您可以在jquery官方文档中了解更多信息: JQuery Deferred Object

    我写这个解决方案,如果有人看到这篇文章可能会有帮助。

    对不起,我的英语:P

        2
  •  6
  •   Shay Erlichmen    15 年前

    首先,您可能需要考虑在单个调用中执行启动代码。
    第二:不要等待,直接调用另一个函数调用。对于上面的代码,应该类似于:

    for (j=1; j <= 7; j++){
      (function(index) {
        $.getJSON('my.php', {id:index}, 
          function(data) {
             $.each(data, function(index2, array){
             ........
             }); 
    
             if (j === 7) {
                initDoneDoMoreStuff()
             }
          });
        })(j)
    } 
    

    或触发器:

    for (j=1; j <= 7; j++){
      (function(index) {
        $.getJSON('my.php', {id:index}, 
          function(data) {
             $.each(data, function(index2, array){
             ........
             }); 
    
             if (j === 7) {
                $(document).trigger("initdone");
             }
          });
        })(j)
    }
    
    $(document).bind("initdone", function() {....});
    
        3
  •  3
  •   user758907    15 年前

    formulario = $('form');
    formulariolongitud = formulario.length;
    i = 0;
    
    formulario.each(function(index, value) {
        $(this).ajaxSubmit({
            async: false,//not sure i
            success: function() {
                i++; 
    
                if(i === formulario.length) {//this is the last one to submit
                    window.location.replace(whatever);
                }
            } 
        });                         
    });
    
        4
  •  1
  •   Alpesh    15 年前

    您可以使用suces(ajax jquery的回调函数)如下:

    $.ajax({
      url: url,
     dataType: 'json',
     data: data,
     success: function(data){
     //Write your code here.
        }
    });
    

    您可以在下面获得ajax的文档-

    ajax

        5
  •  0
  •   Community Mohan Dere    9 年前

    像if(j==7)这样的问题是,第7个请求非常快,甚至其他请求中的一个也很慢。即使您最后一次排队,它也可能不是最后一次完成。

    这个答案似乎适用于所有情况: https://stackoverflow.com/a/3709809/813154