2008-12-30 85 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'); 
        } 
       } 
     }); 
    }); 
}); 

成功函數中的警報顯示正確的城市。