Multiple Async AJAX Calls Best Practice

2019-04-09 14:55发布

I have a question regarding the "Best Practice" for making multiple AJAX calls on a single page.

I need to make 5 isolated calls, asynchronously. I know that $.ajax is async by nature, but I was curious if there's a "cleaner" or "better" way to do multiple AJAX calls.

An example of including multiple AJAX calls is below:

$(function() {
  $.ajax({
    type: "GET",
    url: "https://api.github.com/users/ralvarenga",
    dataType: "json",
    success: function(data) { console.log(data); }
  });
  $.ajax({
    type: "GET",
    url: "https://api.github.com/users/dkang",
    dataType: "json",
    success: function(data) { console.log(data); }
  });
});

Thanks for any help in advance!

1条回答
该账号已被封号
2楼-- · 2019-04-09 15:34

You should use $.when().

$.when($.ajax("/page1.php"), $.ajax("/page2.php")).done(function (a1, a2) {
    //all AJAX requests are finished
});

Or:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
    .then( successFunction, failureFunction );
查看更多
登录 后发表回答