jQuery callback for multiple ajax calls

后端 未结 14 1867
夕颜
夕颜 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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
            }
        });
    });
    

提交回复
热议问题