通过阵列迭代同时执行针对每个条目的请求目的、阵列、迭代

2023-09-10 16:50:53 作者:迎面的心魔惧怕什么

下面是我的问题。我有一个包含我需要查找天气的城市的名称的数组。所以我遍历每个城市和执行AJAX请求来检索天气。

Here is my issue. I have an array containing the name of cities that I need to lookup the weather for. So I'm looping through each city and performing an AJAX request to retrieve the weather.

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循环和成功的功能,这似乎是一个循环被执行的 cities.length 的时间,然后我得到了成功的功能警报。我的目标是通过每个城市的简单循环获取天气和显示它在我的网页以及相关的城市名称。

The issue I'm encountering is that in the success function, I can't access the city name (via cities[cityIdx]). I inserted an alert() in the for loop and the success function and it seems like the loop gets executed cities.length times, then I get the success function alerts. My goal is to simply loop through each city getting the weather and showing it on my page along with the associated city name.

此外,你会建议我应该做的单独内容presentation?

Also, what would you suggest I should do to separate content with presentation?

感谢您。 :)

推荐答案

我怀疑你的问题是类似的例子在的 http://ejohn.org/apps/learn/ 。该指数变量cityIdx在创建for循环处理封闭更新,所以你成功函数运行时间cityIdx将指向数组中的最后一个元素。的解决方案是使用一个评价匿名函数创建一个独立方面,在那里索引值没有更新

I suspect that your problem is similar to the example at http://ejohn.org/apps/learn/. The index variable cityIdx is updated in the closure you create as the for loop is processed, so by the time your function on success is run cityIdx will point to the last element in the array. The solution is to use an evaluated anonymous function to create an independent context, where the index value doesn't get updated.

//...
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)
//...