Chain ajax and execute it in sequence. Jquery Deferred

后端 未结 5 636
旧时难觅i
旧时难觅i 2020-11-30 02:53

I have 3 processes that needs ajax to complete. But it is asynchronous and it fails to do what I wanted to do..

Lets say:

function a(param1, param2)         


        
5条回答
  •  误落风尘
    2020-11-30 03:10

    Here is an wonderfully simple and highly effect AJAX chaining / queue plugin. It will execute you ajax methods in sequence after each other.

    It works by accepting an array of methods and then executing them in sequence. It wont execute the next method whilst waiting for a response.

    //--- THIS PART IS YOUR CODE -----------------------

    $(document).ready(function () {

    var AjaxQ = [];
    AjaxQ[0] = function () { AjaxMethod1(); }
    AjaxQ[1] = function () { AjaxMethod2(); }
    AjaxQ[3] = function () { AjaxMethod3(); }
    
    //Execute methods in sequence
    $(document).sc_ExecuteAjaxQ({ fx: AjaxQ });
    

    });

    //--- THIS PART IS THE AJAX PLUGIN -------------------

    $.fn.sc_ExecuteAjaxQ = function (options) {

    //? Executes a series of AJAX methods in dequence
    
    var options = $.extend({
    
        fx: [] //function1 () { }, function2 () { }, function3 () { }
    
    }, options);
    
    if (options.fx.length > 0) {
    
        var i = 0;
    
        $(this).unbind('ajaxComplete');
        $(this).ajaxComplete(function () {
    
            i++;
            if (i < options.fx.length && (typeof options.fx[i] == "function")) { options.fx[i](); }
            else { $(this).unbind('ajaxComplete'); }
    
        });
    
        //Execute first item in queue
        if (typeof options.fx[i] == "function") { options.fx[i](); }
        else { $(this).unbind('ajaxComplete'); }
    
    } 
    

    }

提交回复
热议问题