I'm using jQuery's $.getJSON()
API to retrieve data from a given URL for a set of utilities. I'd really like to find a way to reuse the code (it's all exactly the same) for each utility. Since the loop is executing without respect to the ajax call, I haven't been able to find a way to retain the looping value.
That description sucks, I know, so here'a a code snippet that defines it a little better:
var utility_types = [ 'Electricity', 'Gas', 'Water' ];
/** Retrieve known utility providers for the given zip code */
for( var i = 0; i < utility_types.length; i++ ) {
var type = utility_types[i];
$.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, function( data, status ) {
alert( 'Processing ' + type );
});
}
I need to find a way to pass the type value into the callback so I can apply the correct syntax. Without that, all 3 loops are executing against the "Water" utility. I know why it's not working, I'm just wondering whether there's a reasonable workaround.
Thanks.
Create a closure
var utility_types = [ 'Electricity', 'Gas', 'Water' ];
function getCallBack(type){
return function(data,status){
alert( 'Processing ' + type );
}
}
/** Retrieve known utility providers for the given zip code */
for( var i = 0; i < utility_types.length; i++ ) {
var type = utility_types[i];
$.getJSON( '/addresses/utilities/' + zip + '/' + type + '.json', null, getCallBack(type));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With