我正在使用AJAX解析json,尽管当我尝试调用传递循环索引值的函数,然后函子将该值推入Global数组时,一切正常,但似乎不是即使console.log()在每个步骤中都按要求打印出所有内容,也可以推入这些值,但是当我检查数组长度时,它始终为0。
//This bit of code is actually inside a function and another ajax success
$.each(updatedData, function(index, element) {
$.ajax({
type: 'GET',
url: 'https://en.wikipedia.org/w/api.php?action=query&prop=extracts&exintro&explaintext&format=json&redirects&callback=?&titles='+updatedData[index],
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
console.log('success wiki');
//getting the pagenumber key value to use the extract value from it
var pagenum = Object.keys(data.query.pages);
if(data.query.pages[pagenum[0]].extract == null)
{
recycleData(index);
}
}
});
});
//this is the function which should push the trash value to the trashData
//the console.log actually logs all the correct values yet still doesn't push
function recycleData(trash){
console.log("sliced - "+trash);
trashData.push(trash);
}
//that's how the array is defined, it's obviously defined before all the functions just in case someone would ask
var trashData = [];
更新:经过一段时间的延迟,我已经测试了数组的长度,所有ajax请求均已完成后才填充该数组,但我需要其他请求来等待此请求完成,以便其他请求将使用更新的数据。此请求是另一个ajax成功,因此请记住这一点。
答案 0 :(得分:0)
如果要在完成操作时执行其他ajax,则可以在上一个ajax的done
函数上调用下一个ajax。
$.ajax({ ... }).done(second_ajax_fn);
还可以设置async:false
,但不建议
答案 1 :(得分:0)
问题可能是您在实际异步请求完成之前正在检查trashData
的值。如果要确保所有请求均已完成然后再检查(或发出更多请求),则需要类似jQuery Deferred - waiting for multiple AJAX requests to finish的东西。