Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/400.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
从Jquery JSON请求推送到Javascript数组_Javascript_Jquery_Arrays - Fatal编程技术网

从Jquery JSON请求推送到Javascript数组

从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

为什么此代码总是返回0

     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);
  });

@彼得·贝利-多!我怎么忘记了那个小的(但非常重要的)部分!这很有道理!谢谢!