Reputation: 842
I want to read from a json file and use its values to draw triangles. While being in the routine i can print out the value, outside of it, it won't work any more. My code:
faces=new Array(40000);
$.getJSON('file.json', function(data) {
$.each(data.faces, function(i, f) {
faces[i]=new Array(3);
faces[i][1]=data.faces[i].f1;
faces[i][2]=data.faces[i].f2;
faces[i][3]=data.faces[i].f3;
//alert(faces[1][1]); works here
});
});
//alert(faces[1][1]); doesn't work here, console says faces[1][1] is undefined
How can I fix this?
Upvotes: 0
Views: 65
Reputation: 1064
Simple change,
faces=new Array(40000);
$.getJSON('file.json', function(data) {
$.each(data.faces, function(i, f) {
faces[i]=new Array(3);
faces[i][1]=f.f1;
faces[i][2]=f.f2;
faces[i][3]=f.f3;
});
});
Use f instead of data.faces inside $.each
Upvotes: -1
Reputation: 45083
Your call to actually get the JSON, in the second case, is taking longer than it takes to get to the point of usage outside of the "success"/"complete" callback, due to the asynchronicity of getJSON
, so the value(s) is/are naturally undefined until the function returns, hence the "success"/"complete" function.
Upvotes: 0
Reputation: 186
That happens because getJSON is async.
try to use the jquery ajax method with async property defined.
$.ajax({
type: "GET",
url: remote_url,
async: false,
success : function(data) {
remote = data;
}
});
Upvotes: 0
Reputation: 23322
The call to $.getJSON
is asynchronous, you only have your faces
array populated inside the callback as you already noticed.
What you could do is:
faces=new Array(40000);
$.getJSON('file.json', function(data) {
$.each(data.faces, function(i, f) {
faces[i]=new Array(3);
faces[i][1]=data.faces[i].f1;
faces[i][2]=data.faces[i].f2;
faces[i][3]=data.faces[i].f3;
//alert(faces[1][1]); works here
});
someFunction();
});
someFunction() {
alert(faces[1][1]);
}
Hope it helps.
Upvotes: 2