Make sure first ajax function finishes before second one

前端 未结 9 1242
無奈伤痛
無奈伤痛 2021-01-18 01:41

I have a JavaScript function that makes two consecutive Ajax requests using jQuery. I want to make sure that the first request has loaded before the second function is call

9条回答
  •  逝去的感伤
    2021-01-18 02:17

    Edit: Misread the question; my bad. If you ever want to have two AJAX requests executed concurrently but run a callback only after both have finished, this is how you do it!

    Try this:

    var completedCount = 0;
    var callback = function()
    {
        completedCount++;
        if (completedCount == 2)
        {
            // Do something.
        }
    };
    
    $.post('url-1', {}, callback);
    $.post('url-2', {}, callback);
    

提交回复
热议问题