jquery - Javascript fetch JSON array -


i'm trying fetch json-array via ajax. test.php returns:

[{"name":"james","age":24},{"name":"peter","age":30}] 

my javascript looks this:

var persons=new array(); $.getjson("../../api/test.php", function(data){         $.each(data, function(index,value){                     persons.push(new person(value.name,value.age));                 });     }); 

problem when later call persons.length, cannot read property 'length' of undefined. when copy/paste output of test.php browser local variable, works fine:

var content=[{"name":"james","age":24},{"name":"peter","age":30}]; for(var i=0; i<content.length; i++)     persons.push(new person(content[i].name,content[i].age)); 

what doing wrong?

this issue scope. if "var persons" declared within function in function's scope. double check declared, , trying access it.

for further reading see: http://coding.smashingmagazine.com/2009/08/01/what-you-need-to-know-about-javascript-scope/

edit: don't believe asynchronous call $.getjson cause of issue because persons.length 0 , persons not undefined.

var persons = new array(); print persons.length; // ==> 0 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -