这是我的问题。我有一个数组,其中包含我需要查找天气的城市名称。因此,我遍历每个城市并执行 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' );
}
}
});
}
});
我遇到的问题是,在成功函数中,我无法访问城市名称(通过 cities[cityIdx])。我在 for 循环和成功函数中插入了一个 alert(),看起来循环执行了 cities.length 次,然后我得到了成功函数警报。我的目标是简单地遍历每个城市获取天气并将其与相关城市名称一起显示在我的页面上。
此外,您建议我应该如何将内容与表示分开?
谢谢。 :)
最佳答案
我怀疑您的问题与 http://ejohn.org/apps/learn/ 中的示例类似.索引变量 cityIdx 在处理 for 循环时在您创建的闭包中更新,因此当您的函数成功运行时,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)
//...
关于javascript - 在对每个条目执行请求时迭代数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/400989/