我有一个嵌套的ajax请求.第一个请求返回带有设备的列表,对于每个设备,我执行另一个ajax请求以获取更多数据.当嵌套请求成功时,我将数据附加到a 我需要某种事件来告诉我所有请求何时完成.我怎样才能做到这一点?请参阅下面的代码
jfriend00..
8
您可以使用promises并 基本思想是将每个ajax调用返回的promise收集到一个数组中.然后使用jQuery 注意,我还从内部ajax调用中删除了成功处理程序,因为您可以处理处理程序中的所有结果 您可以使用promises并 基本思想是将每个ajax调用返回的promise收集到一个数组中.然后使用jQuery 注意,我还从内部ajax调用中删除了成功处理程序,因为您可以处理处理程序中的所有结果.
$.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listAllDevices")',
dataType: 'json',
success: function (data) {
$.each(data.devices.device, function (index, value) {
$.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listLokationLabelsForDevice")' + '?uuid=' + value.uuid,
dataType: 'json',
success: function (data3) {
//Append to table
}
});
});
$.when()
查看所有ajax调用何时完成,如下所示:$.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listAllDevices")',
dataType: 'json',
success: function (data) {
var promises = [];
$.each(data.devices.device, function (index, value) {
promises.push($.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listLokationLabelsForDevice")' + '?uuid=' +
value.uuid,
dataType: 'json',
}));
});
$.when.apply($, promises).done(function() {
// all ajax results are done here
// results from each ajax call are in order in
// arguments[0], arguments[1], ...
// you can now append them all to the table
});
}
});
$.when
让jQuery告诉你所有这些promise何时被解析并从中收集所有返回的结果并按照你请求它的顺序保存所有数据.然后,当.done()
调用callback 时$.when()
,所有数据可用,您可以按顺序一次处理所有内容..done()
.
$.when()
查看所有ajax调用何时完成,如下所示:$.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listAllDevices")',
dataType: 'json',
success: function (data) {
var promises = [];
$.each(data.devices.device, function (index, value) {
promises.push($.ajax({
type: 'GET',
url: '@Url.Content("~/Service/listLokationLabelsForDevice")' + '?uuid=' +
value.uuid,
dataType: 'json',
}));
});
$.when.apply($, promises).done(function() {
// all ajax results are done here
// results from each ajax call are in order in
// arguments[0], arguments[1], ...
// you can now append them all to the table
});
}
});
$.when
让jQuery告诉你所有这些promise何时被解析并从中收集所有返回的结果并按照你请求它的顺序保存所有数据.然后,当.done()
调用callback 时$.when()
,所有数据可用,您可以按顺序一次处理所有内容..done()
.
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有