Wait until all jQuery Ajax requests are done?

后端 未结 21 2402
离开以前
离开以前 2020-11-21 04:39

How do I make a function wait until all jQuery Ajax requests are done inside another function?

In short, I need to wait for all Ajax requests to be done before I exe

21条回答
  •  耶瑟儿~
    2020-11-21 05:18

    A little workaround is something like this:

    // Define how many Ajax calls must be done
    var ajaxCalls = 3;
    var counter = 0;
    var ajaxCallComplete = function() {
        counter++;
        if( counter >= ajaxCalls ) {
                // When all ajax calls has been done
            // Do something like hide waiting images, or any else function call
            $('*').css('cursor', 'auto');
        }
    };
    
    var loadPersons = function() {
            // Show waiting image, or something else
        $('*').css('cursor', 'wait');
    
        var url = global.ctx + '/loadPersons';
        $.getJSON(url, function(data) {
                // Fun things
        })
        .complete(function() { **ajaxCallComplete();** });
    };
    
    var loadCountries = function() {
        // Do things
        var url = global.ctx + '/loadCountries';
        $.getJSON(url, function(data) {
                // Travels
        })
        .complete(function() { **ajaxCallComplete();** });
    };
    
    var loadCities = function() {
        // Do things
        var url = global.ctx + '/loadCities';
        $.getJSON(url, function(data) {
                // Travels
        })
        .complete(function() { **ajaxCallComplete();** });
    };
    
    $(document).ready(function(){
        loadPersons();
        loadCountries();
        loadCities();
    });
    

    Hope can be useful...

提交回复
热议问题