从Jquery JSON请求推送到Javascript数组
为什么此代码总是返回0从Jquery JSON请求推送到Javascript数组,javascript,jquery,arrays,Javascript,Jquery,Arrays,为什么此代码总是返回0 var possibleMatches = new Array(); $.getJSON('getInformation.php', function(data) { $.each(data, function(i){ possibleMatches.push(data[i]); }) }); alert(possibleMatches.length); 虽然我可以在$each中移动或添加“alert(possibleMatch
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length);
虽然我可以在$each中移动或添加“alert(possibleMatches.length);”,但它将输出正确数量的元素
我只是好奇为什么这些值没有像我预期的那样进入数组。我肯定这是一个局部变量和全局变量的问题,只是不知道为什么
基本上,它试图做的是用数据结果填充可能的匹配数组
谢谢 异步性。行
警报(可能匹配长度)在执行$.getJSON()
的成功回调之前执行code>
因此,要准确地获取警报报告,只需移动它
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
})
// To here
alert(possibleMatches.length);
});
// From here
记住,AJAX中的第一个A代表“异步”$。getJSON
执行异步调用,其回调在使用的xmlhttprequest完成时执行:
var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) { // <-- this will run later
$.each(data, function(i){
possibleMatches.push(data[i]);
})
});
alert(possibleMatches.length); // this will call immediately
var-possibleMatches=new-Array();
$.getJSON('getInformation.php',function(data){/jetJSON请求是异步的,它在警报运行后完成。如果您想要累积警报,它应该在getJSON
的回调中,如下所示:
$.getJSON('getInformation.php', function(data) {
$.each(data, function(i){
possibleMatches.push(data[i]);
});
alert(possibleMatches.length);
});
@彼得·贝利-多!我怎么忘记了那个小的(但非常重要的)部分!这很有道理!谢谢!