jQuery callback for multiple ajax calls

后端 未结 14 1633
夕颜
夕颜 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:37
    $.ajax({type:'POST', url:'www.naver.com', dataType:'text', async:false,
        complete:function(xhr, textStatus){},
        error:function(xhr, textStatus){},
        success:function( data ){
            $.ajax({type:'POST', 
                ....
                ....
                success:function(data){
                    $.ajax({type:'POST',
                        ....
                        ....
                }
            }
        });
    

    I'm sorry but I can't explain what I worte cuz I'm a Korean who can't speak even a word in english. but I think you can easily understand it.

    0 讨论(0)
  • 2020-11-22 09:37
    async   : false,
    

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

    0 讨论(0)
  • 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/

    0 讨论(0)
  • 2020-11-22 09:39

    Ok, this is old but please let me contribute my solution :)

    function sync( callback ){
        syncCount--;
        if ( syncCount < 1 ) callback();
    }
    function allFinished(){ .............. }
    
    window.syncCount = 2;
    
    $.ajax({
        url: 'url',
        success: function(data) {
            sync( allFinished );
        }
    });
    someFunctionWithCallback( function(){ sync( allFinished ); } )
    

    It works also with functions that have a callback. You set the syncCount and you call the function sync(...) in the callback of every action.

    0 讨论(0)
  • 2020-11-22 09:40

    I asked the same question a while ago and got a couple of good answers here: Best way to add a 'callback' after a series of asynchronous XHR calls

    0 讨论(0)
  • 2020-11-22 09:42

    Not seeing the need for any object malarky myself. Simple have a variable which is an integer. When you start a request, increment the number. When one completes, decrement it. When it's zero, there are no requests in progress, so you're done.

    $('#button').click(function() {
        var inProgress = 0;
    
        function handleBefore() {
            inProgress++;
        };
    
        function handleComplete() {
            if (!--inProgress) {
                // do what's in here when all requests have completed.
            }
        };
    
        $.ajax({
            beforeSend: handleBefore,
            complete: function () {
                // whatever
                handleComplete();
                // whatever
            }
        });
        $.ajax({
            beforeSend: handleBefore,
            complete: function () {
                // whatever
                handleComplete();
                // whatever
            }
        });
        $.ajax({
            beforeSend: handleBefore,
            complete: function () {
                // whatever
                handleComplete();
                // whatever
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题