最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Pushing to Javascript Array from Jquery JSON request - Stack Overflow

programmeradmin2浏览0评论

Why does this code always return 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);" inside the $.each and it will output the correct number of elements.

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.

thanks!

Why does this code always return 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);" inside the $.each and it will output the correct number of elements.

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.

thanks!

Share Improve this question asked Mar 9, 2010 at 16:58 psiko.scweekpsiko.scweek 851 silver badge5 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Asynchronicity. The line alert(possibleMatches.length); executes before the success callback for $.getJSON() executes.

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"

$.getJSON performs an asynchronous call, whose callback is executed on pletion of the xmlhttprequest used:

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. If you want an accruate alert, it should be in your callback for getJSON like this:

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

评论列表(0)

  1. 暂无评论