jQuery callback for multiple ajax calls

后端 未结 14 1620
夕颜
夕颜 2020-11-22 09:18

I want to make three ajax calls in a click event. Each ajax call does a distinct operation and returns back data that is needed for a final callback. The calls themselves ar

14条回答
  •  隐瞒了意图╮
    2020-11-22 09:38

    I got some good hints from the answers on this page. I adapted it a bit for my use and thought I could share.

    // lets say we have 2 ajax functions that needs to be "synchronized". 
    // In other words, we want to know when both are completed.
    function foo1(callback) {
        $.ajax({
            url: '/echo/html/',
            success: function(data) {
                alert('foo1');
                callback();               
            }
        });
    }
    
    function foo2(callback) {
        $.ajax({
            url: '/echo/html/',
            success: function(data) {
                alert('foo2');
                callback();
            }
        });
    }
    
    // here is my simplified solution
    ajaxSynchronizer = function() {
        var funcs = [];
        var funcsCompleted = 0;
        var callback;
    
        this.add = function(f) {
            funcs.push(f);
        }
    
        this.synchronizer = function() {
            funcsCompleted++;
            if (funcsCompleted == funcs.length) {
                callback.call(this);
            }
        }
    
        this.callWhenFinished = function(cb) {
            callback = cb;
            for (var i = 0; i < funcs.length; i++) {
                funcs[i].call(this, this.synchronizer);
            }
        }
    }
    
    // this is the function that is called when both ajax calls are completed.
    afterFunction = function() {
        alert('All done!');
    }
    
    // this is how you set it up
    var synchronizer = new ajaxSynchronizer();
    synchronizer.add(foo1);
    synchronizer.add(foo2);
    synchronizer.callWhenFinished(afterFunction);
    

    There are some limitations here, but for my case it was ok. I also found that for more advanced stuff it there is also a AOP plugin (for jQuery) that might be useful: http://code.google.com/p/jquery-aop/

提交回复
热议问题