简体   繁体   English

从Jquery JSON请求推送到Javascript数组

[英]Pushing to Javascript Array from Jquery JSON request

Why does this code always return 0? 为什么这段代码总是返回0?

     var possibleMatches = new Array();
  $.getJSON('getInformation.php', function(data) {
   $.each(data, function(i){
    possibleMatches.push(data[i]);
   })
  });
  alert(possibleMatches.length);

Though I can move or add "alert(possibleMatches.length);" 虽然我可以移动或添加“alert(possibleMatches.length);” inside the $.each and it will output the correct number of elements. 在$ .each中,它将输出正确数量的元素。

I'm just curious as to why it the values aren't going into the array as I expected. 我只是好奇为什么价值不像我预期的那样进入数组。 I'm sure its a local variable vs. global variable issue, just not sure why. 我确定它是局部变量与全局变量问题,只是不确定原因。

Basically, what this is trying to do is fill the possibleMatches array with the data results. 基本上,这是尝试做的是使用数据结果填充possibleMatches数组。

thanks! 谢谢!

Asynchronicity. 异步。 The line alert(possibleMatches.length); alert(possibleMatches.length); executes before the success callback for $.getJSON() executes. $.getJSON()执行成功回调之前执行。

So, to have your alert report accurately, just move it. 因此,要准确地提供警报报告,只需移动它即可。

var possibleMatches = new Array();
$.getJSON('getInformation.php', function(data) {
  $.each(data, function(i){
    possibleMatches.push(data[i]);
  })

  // To here
  alert(possibleMatches.length);
});
// From here

Remember, the first A in AJAX stands for "Asynchronous" 请记住,AJAX中的第一个A代表“异步”

$.getJSON performs an asynchronous call, whose callback is executed on completion of the xmlhttprequest used: $.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

The jetJSON request is asynchronous, it finished after your alert runs. jetJSON请求是异步的,它在警报运行后完成。 If you want an accruate alert, it should be in your callback for getJSON like this: 如果你想要一个accruate警报,它应该在你的getJSON回调中,如下所示:

  $.getJSON('getInformation.php', function(data) {
   $.each(data, function(i){
    possibleMatches.push(data[i]);
   });
   alert(possibleMatches.length);
  });

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

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