I have the following script which is not working for some reason:
success: function( widget_data )
{
if( widget_data.d[0] ) {
var j = 0;
for ( j = 0; j <= widget_data.d.length - 1; j++ ) {
$.getScript( "js/" + widget_data.d[j].script, function() {
// this line is complaining about .widget_id
alert(widget_data.d[j].widget_id);
});
// but this line works fine...
alert(widget_data.d[j].widget_id);
}
}
}
I get an error on the following line, with one withing .getScript:
alert(widget_data.d[j].widget_id);
The error message is:
Cannot read property 'widget_id' of undefined
But the strange thing is, the following alerts work fine and return the correct values:
alert(widget_data.d[j].widget_id);
What am I doing wrong?
The getScript call runs asynchronously capturing the variable
jnot it’s value at the time it is invoked. This means thatjlikely has the value that terminated the loop at the time the call returns. You should call thegetScriptwithin a function so you can capture the value ofjrather than it’s reference. Actually, it’s probably better to actually capture the “widget” object itself, as you can see in the code sample.