多个异步AJAX调用最佳实践 [英] Multiple Async AJAX Calls Best Practice

查看:68
本文介绍了多个异步AJAX调用最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对在单个页面上进行多个AJAX调用的最佳实践有疑问。

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

我需要异步进行5次隔离调用。我知道$ .ajax本质上是异步的,但我很好奇是否有更清洁或更好的方式来进行多个AJAX调用。

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.

一个例子包括多个AJAX调用如下:

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!

推荐答案

您应该使用 $ .when()

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

或者:

$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) )
    .then( successFunction, failureFunction );

这篇关于多个异步AJAX调用最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆