I am using the jQuery API $.getJSON()to retrieve data from a given URL for a set of utilities. I would really like to find a way to reuse the code (everything is exactly the same) for each utility. Since the loop runs without respect for the ajax call, I could not find a way to save the loop value.
This description sucks, I know, so there is a piece of code here that defines it a little better:
var utility_types = [ 'Electricity', 'Gas', 'Water' ];
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 a callback so that I can apply the correct syntax. Without this, all three loops run against the Water utility. I know why it does not work, I'm just wondering if there is a reasonable solution.
Thank.
source
share