繁体   English   中英

在AJAX成功的函数中使用时,数组内容不会更改

[英]Array contents don't change when used in a function in AJAX success

我正在使用AJAX解析json,一切正常但是当我尝试调用一个函数,我传递循环的索引值然后函数将此值推入全局数组时,似乎它没有推动这些值即使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成功,所以请记住。

如果你想在完成时做其他的ajax,你可以在之前的ajax的done函数上调用你的下一个ajax调用。

$.ajax({ ... }).done(second_ajax_fn);

您也可以设置async:false但不建议这样做

问题很可能是您在实际的异步请求完成之前检查了trashData的值。 如果你想确保所有请求都已完成然后检查它(或发出更多请求),你需要像jQuery Deferred这样的东西- 等待多个AJAX请求完成

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM