我遇到了一个问题。我有一个包含城市名称的数组,我需要查找每个城市的天气。所以我正在循环遍历每个城市,并执行 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 次,然后我得到了成功函数的警报。我的目标只是循环遍历每个城市,获取天气信息,并将其显示在我的页面上以及相关的城市名称。
此外,您建议我应该如何分离内容和演示?
谢谢。 :)