按顺序运行AJAX

时间:2017-06-06 02:26:32

标签: javascript jquery ajax

我需要按顺序运行2个AJAX。只有在加载页面时才会调用第一个AJAX。调用第一个AJAX或用户点击页面上的某些按钮后,将调用第二个AJAX。

我写了以下内容,但每次调用第二个AJAX时都会调用第一个AJAX。

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

//Second AJAX
$.when(GetFirstAJAX()).then(function()
{
  $.ajax({
    ...
  });
});

1 个答案:

答案 0 :(得分:1)

你可以在done方法中运行第二个ajax,它可以链接在第一个ajax上,如下所示:

// 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
  })
})