代码之家  ›  专栏  ›  技术社区  ›  jul

当所有Ajax调用完成时,如何触发函数?

  •  1
  • jul  · 技术社区  · 15 年前

    我正在用jquery调用几个Ajax搜索服务,并希望触发一个函数,在所有调用完成时合并结果(某种回调函数,等待所有回调返回)。实现这一目标的最佳方法是什么?

    谢谢

    7月

    3 回复  |  直到 15 年前
        1
  •  1
  •   sje397    15 年前

    $.ajax({
      // ..
      success: function() {
        if(--counter == 0) handleComplete();
        // ...
      }
    });
    
    // 2 other similar ajax calls here
    
    function handleComplete() {
      // this is done when all are complete
    }
    

        2
  •  0
  •   samy    15 年前

        3
  •  0
  •   T.J. Crowder    15 年前

    ajaxComplete event

    live copy

    jQuery(function($) {
      var count = 0;
    
      display("Hooking up handler");
      $(document.body).ajaxComplete(function(event, xhr, options) {
        ++count;
        display("Got a completion, new counter value = " + count);
      });
      display("Doing three ajax requests.");
      $.ajax({
        url: "http://jsbin.com/aciyu4"
      });
      $.ajax({
        url: "http://jsbin.com/aciyu4"
      });
      $.ajax({
        url: "http://jsbin.com/aciyu4"
      });
    
      function display(msg) {
        $("<p/>").html(msg).appendTo(document.body);
      }
    });​
    

    count closure