Friday 15 February 2013

jquery - Javascript Array Variable Scope -



jquery - Javascript Array Variable Scope -

this question has reply here:

how homecoming response asynchronous call? 11 answers

i have problem array variable scope in javascript. here's code

class="snippet-code-js lang-js prettyprint-override">var features = new array(); var x = 0; $.ajax({ async: true, url: domain + "client/applications/getfeatures", datatype: 'json', success: function(data) { if (data.code == 200) { $.each(data.data, function(i, val) { features[x] = val.features_value; x++; }); } } }); alert(features[0]);

the result of pop "undefine". have solutions ? give thanks you

you problem isn't variable scope, it's async code.

your alert fired before success callback, features hasn't been set yet. instead:

$.ajax({ // ... other ajax opts success: function(data){ var features = new array(); if(data.code == 200){ var x = 0; $.each(data.data, function(i, val){ features[x]=val.features_value; x++; }); } alert(features[0]); } });

javascript jquery ajax

No comments:

Post a Comment