2008-12-30 84 views
4

这是我的问题。我有一个包含我需要查找天气的城市名称的数组。所以我在每个城市循环播放并执行AJAX请求来检索天气。在执行每个条目的请求时遍历数组

var LOCATION = 'http://www.google.com/ig/api?weather='; 

$(document).ready(function() { 
    for(var cityIdx = 0; cityIdx < cities.length; cityIdx++) { 
     $.ajax({ 
      type: 'GET', 
      url: LOCATION + cities[ cityIdx ], 
      dataType: 'xml', 
      success: function(xml) { 
       if($(xml).find('problem_cause') != 0) { 
        // Do what I want with the data returned 
        var weather = $(xml).find('temp_c').attr('data'); 
       } 
      } 
     }); 
    } 
}); 

我遇到的问题是,在成功功能,我无法访问城市名称(通过城市[cityIdx])。我在for循环和成功函数中插入了alert(),看起来好像循环得到执行cities.length次,然后我得到了成功函数警报。我的目标是简单地循环访问每个城市获取天气并将其显示在我的页面上以及相关的城市名称。

此外,你会建议我应该如何将内容与演示文稿分开?

谢谢。 :)

回答

5

我怀疑你的问题是类似的http://ejohn.org/apps/learn/的例子。在处理for循环时,索引变量cityIdx将在您创建的闭包中更新,因此,当成功执行函数时,cityIdx将指向数组中的最后一个元素。解决方案是使用评估的匿名函数来创建独立的上下文,其中索引值不会更新。

//... 
success: (function(cities, idx) { 
    return function(xml) { 
     if($(xml).find('problem_cause') != 0) { 
     // Do what I want with the data returned 
     // use cities[idx] 
     var weather = $(xml).find('temp_c').attr('data'); 
     } 
    }; 
    })(cities, cityIdx) 
//... 
1

最简单的事情就是让你的AJAX请求返回城市名称。

1

由于各种原因,我会尝试将成功函数提取到单独定义的函数中,然后在包含城市名称的ajax调用中创建一个闭包。因此,首先,一个独立的成功处理程序:

function city_success(xml, name) { 
    // your success handling code here 
} 

,然后更改成功的Ajax调用绑定:

success: function (xml) { city_success(xml, cities[ cityIdx ]); }, 
5

由于JavaScript使用功能关闭,我发现最简单的方法对我来说是只是包装的内容for循环中的内联函数会将当前的城市名字给一个变量,它会永远有机会获得。

$(document).ready(function() { 
    for (var cityIdx = 0; cityIdx < cities.length; cityIdx++) { 
     new function() { 
      var currentCity = cities[cityIdx]; 
      $.ajax({ 
       type: 'GET', 
       url: LOCATION + currentCity, 
       dataType: 'xml', 
       success: function(xml) { 
        alert(currentCity); 
        if ($(xml).find('problem_cause') != 0) { 
         // Do what I want with the data returned 
         var weather = $(xml).find('temp_c').attr('data'); 
        } 
       } 
      }); 
     }(); // the "();" calls the function we just created inline 
    } 
}); 
+0

即将发布相同的答案...良好的电话 – 2008-12-30 18:48:29

+0

我认为你应该删除'新' – Javier 2008-12-30 18:56:53

3

为什么不使用jQuery遍历数组?使用jQuery的每个函数:

var LOCATION = 'http://www.google.com/ig/api?weather='; 

$(document).ready(function() { 

    $.each(cities, function() { 
    //assign the current city name to a variable 
     var city = this; 
     $.ajax({ 
       type: 'GET', 
       url: LOCATION + city, 
       dataType: 'xml', 
       success: function(xml) { 
        if($(xml).find('problem_cause') != 0) { 
         alert(city); 
          // Do what I want with the data returned 
         var weather = $(xml).find('temp_c').attr('data'); 
        } 
       } 
     }); 
    }); 
}); 

成功函数中的警报显示正确的城市。