制作多个AJAX请求的最实用方法

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

$.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请求?

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

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

这将在您的代码中添加您需要的打孔。 希望这可以帮助。 保罗

你可以做一个技巧。 使用它时必须小心,这样你就不会搞砸了。 我给你一个整体逻辑,你可以完成实现。

 function fireAjax(functions_list) { // The variable functions_list will contain the list of functions like "getUsers,getStatsData,getTopnews" $.ajax({ //bla bla bla data:{"getUsers[group_id]":group_id,"getUsers[foo]":bar,"getStatsData[limit]":limit}, success:function(json_result) { // You have to form the result also according to the function names like /* { getUsers:[user1,user2,user3....], getStatsData[stats1,stats2.....], bla bla bla... } */ // handle your responses here one by one } }) }