我试图用多个其他Ajax请求中的数据发送数据。当调用sendDataOffAjax()
时,问题出现了,没有实际的数据被发送,因为它在任何其他功能发生改变以添加数据之前就会关闭。我可以通过在任何地方使用asyn: false
来轻松解决此问题,但从我阅读的内容来看,这是不好的做法。等到所有的Ajax完成处理在另一个Ajax内部,然后发送数据
这里是我的代码:
let requests = [];
$.ajax({
url: someUrl,
method: 'GET',
dataType: 'json',
complete: function (data) {
if (data.exists) {
if (condition) {
requests.push(anotherAjax());
}
if (condition) {
requests.push(someDifferentAjax());
}
}
requests.push(alwaysRunAjax());
}
}).done(function() {
$.when.apply($, requests).done(function() {
sendDataOffAjax();
});
});
继承人的外观anotherAjax()
像(其他所有的Ajax请求也这个样子):
function anotherAjax() {
return $.ajax({
url: someUrl,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'GET',
dataType: 'json',
complete: function (data) {
if (data.exists) {
toSendData.data['NEW_DATA'] = {
'data': data.responseJSON
}
}
//send complete signal?
}
})
}
我怎么可能让它等到所有数据通过其他Ajax请求添加,然后启动sendDataOffAjax()
。
日志看起来是这样的:
Data sent
anotherAjax Data added
alwaysRunAjax Data added
someDifferentAjax Data added
请勿使用'complete'或'done'。总是使用'然后'。 – Bergi