weixin_33698823 2017-06-06 02:26 采纳率: 0%
浏览 23

按顺序运行AJAX

I need to run 2 AJAX in order. The first AJAX will only be called once when the page is loaded. The second AJAX will be called after the first AJAX was called or when user clicked some buttons on the page.

I have written the following, but the first AJAX will be called each time when the second AJAX is called.

var GetFirstAJAX = function() {
  var deferred = $.Deferred();
  $.ajax({
    ...
  success: deferred.resolve();
  error: deferred.reject();
    ...
  });
  return deferred.promise();
};

//Second AJAX
$.when(GetFirstAJAX()).then(function()
{
  $.ajax({
    ...
  });
});
  • 写回答

1条回答 默认 最新

  • weixin_33697898 2017-06-06 03:16
    关注

    You can just run the second ajax in the done method that can be chained on the first ajax like so:

    // first ajax
    $.ajax({
      // .. ajax details
    }).done(function(res){
      // res is the result of the first ajax
      // do something with it (e.g console.log) or call second ajax call
      $.ajax({
        // .. second ajax details
      }).done(function(res2) { 
        // .. the rest of logic
      })
    })

    </div>
    
    评论

报告相同问题?