制作多个AJAX请求的最实用方法 [英] Most practical way to make multiple AJAX requests

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

问题描述

这里有一个jQuery noobie ..我想知道是否有办法将多个AJAX请求合并到一个JSON对象中?例如。如果我有......

sort of a jQuery noobie here.. I am wondering if there is a way to merge multiple AJAX requests into one JSON object? For example. If I have...

$.ajax({
  dataType: 'json',
  url: "test1.html",
  context: document.body
}).done(function() { 
  $(this).addClass("done");
});

$.ajax({
  dataType: 'json',
  url: "test2.html",
  context: document.body
}).done(function() { 
  $(this).addClass("done");
});

我可以将两者合并,所以我只有一个JSON对象。如果是这样,这无论如何都会有益吗?或者是否有更实用的方法来处理多个AJAX请求?

Is there I can merge the two so I only have one JSON object. And if so would this be beneficial in anyway? Or is there a more practical way to handle multiple AJAX requests?

推荐答案

每个ajax函数都需要更改以返回Deferred对象完成后管理呼叫的回调。 done()函数链接在 $。当时声明代码在所有ajax调用都有时运行已成功完成。

Each of the ajax functions need changed to return a Deferred object which manages the callbacks for a call after all complete. The done() function is chained off of $.when to declare the code to run when all your ajax calls have completed successfully.

done()函数接收每个ajax调用的参数。每个参数都包含一个参数数组,这些参数将传递给该ajax调用的成功回调。因此,如果您查阅文档,则会看到延迟对象的强大功能

The done() function receives an argument for each of the ajax calls. Each argument holds an array of the arguments that would be passed to that ajax call’s success callback. So if you consult the documentation you see the power of Deferred objects.

这将在您的代码中添加您需要的打孔。
希望这会有所帮助。
paul

This will add the punch you need in your code. Hope this helps. paul

这篇关于制作多个AJAX请求的最实用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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