循环中的异步性

Rob*_*son 5 ajax jquery

我正在使用jQuery的$.getJSON()API从给定的URL中检索一组实用程序的数据.我真的想找到一种方法来重用每个实用程序的代码(它们都完全相同).由于循环正在执行而不考虑ajax调用,因此我无法找到保留循环值的方法.

我知道,那个描述很糟糕,所以这里是一个代码片段,它将它定义得更好一些:

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 );
  });
}
Run Code Online (Sandbox Code Playgroud)

我需要找到一种方法将类型值传递给回调,以便我可以应用正确的语法.没有它,所有3个循环都在针对"Water"实用程序执行.我知道为什么它工作,我只是想知道是否有一个合理的解决办法.

谢谢.

Zim*_*bao 3

创建一个闭包

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));
}
Run Code Online (Sandbox Code Playgroud)