How to wait for ajax success handler to finish before executing another

前端 未结 4 1291
梦如初夏
梦如初夏 2021-01-18 21:50

I have the following scenario in my javascript:

  1. Ajax loads a record.
  2. Based on the return value of that record, another ajax call grabs a html form tha
相关标签:
4条回答
  • 2021-01-18 22:47

    Do something like this where you use nested functions in the success callback:

    $.ajax({
        url: "somewhere"
        success: function(data1){
            //Use data1 to determine ajax request #2
            $.ajax({
                url: "somewhere else"
                success: function(data2){
                    //Do stuff with data1 and data2
                 }
             });
          }
    });
    
    0 讨论(0)
  • 2021-01-18 22:47

    You can use jQuery promises, i.e.:

    var loadingData = $.get(loadDataUrl);
    var loadingHtml = $.get(grabHtmlUrl);
    $.when(loadingData, loadingHtml).done(function(loadDataResult, loadHtmlResult){
         //add the html to the dom
         //use data to update the dom as you please       
    });
    

    Note: $.get is just a version of $.ajax that performs a get request

    Sources: http://api.jquery.com/deferred.promise/

    http://api.jquery.com/jquery.get/

    http://api.jquery.com/jquery.ajax/

    http://api.jquery.com/jquery.when/

    0 讨论(0)
  • 2021-01-18 22:49

    Bit late to answer, but

    Much better way is to use promises as the way they designed to be used

    Pseudo implementation

    var promise = $.ajax({
        url: url,
        data: data
    }).done(function (data) {
        var result = process(data);
        return $.ajax({
            url: url,
            data: result
        });
    }).done(function (data) {
        // data is the result of second ajax call
    });
    
    0 讨论(0)
  • 2021-01-18 22:56

    You should use when or success not both. It sounds like (although code samples would make this clearer) you are attaching two separate listeners to the ajax call, but you only want one to execute after the other.
    I'd either roll both into one event like:

    $.ajax( ... , function(){
        // success
        // prep stuff here
        $.ajax( ... , function(){
            // second success
            // do final stuff here
        });
    });
    

    Or wrap you ajax call inside another promise (this may require a bit more reading around jQuery promises).

    But if you do something like

    $.when($.ajax( ... , function(){
        // thing a
    }).then(function(){
        // thing b
    });
    

    Thing a and b will execute at the same time, because they are designed for pretty much the same thing.

    0 讨论(0)
提交回复
热议问题