【发布时间】:2021-03-26 07:42:57
【问题描述】:
我有一个循环遍历数组并为数组的每个对象调用 php 脚本的函数。 php 脚本正在从 google maps api 获取 Lat/Lng,所以我需要限制 api 调用。该列表可能很长(当前为 300)。我想在脚本运行时更新用户。
在我的成功回调中,我可以通过控制台记录每个响应,但我想为用户更新的元素只会更新一次。
有没有办法在每次成功响应后更新用户?
这是我的功能:
$('#agents-lat-lng').click(function() {
var data = {
'action': 'getLatLng'
}
$.ajax({
url: ajax_url,
type: 'post',
data: data,
dataType: 'json',
success: function(response){
for ( var i = 0, l = response.query.length; i < l; i++ ) {
$.when(updateLatLngDB(response.query[i]))
.done(function(dataFromResponses){
console.log('1 ', dataFromResponses[0])
}).fail(function(response){
console.error(response);
});
}
},
error: function (textStatus, errorThrown) {
console.log(textStatus, errorThrown)
}
})
})
这是第二个功能:
function updateLatLngDB(query) {
var deferred = new $.Deferred()
var dataFromResponses = []
var count = 0
var data = {
'action': 'updateLatLng',
'agent': query
}
$.ajax({
url: ajax_url,
type: 'post',
data: data,
dataType: 'json',
cache: false,
async: false,
success: function(response){
count++
console.log('count ', count)
$('#process-upload-response').text(count)
dataFromResponses.push(response)
},
error: function (textStatus, errorThrown) {
console.log(textStatus, errorThrown)
deferred.reject(response)
$('#process-upload-response').html(textStatus, errorThrown)
}
})
deferred.resolve(dataFromResponses)
return deferred.promise()
}
我已经尝试了从 Deferred 到 setTimout 的所有方法,但是当数组中的每个项目都得到处理时,我无法更新 #process-upload-response。只有在所有响应完成后才会更新。
更新:我已经能够通过将其添加到 for 循环来使其工作
(function(i){
window.setTimeout(function(){
promises.push(updateLatLngDB(response.query[i],response.query.length));
}, i * 1000);
}(i));
【问题讨论】:
标签: javascript jquery ajax asynchronous