2015-05-29 101 views
1

我很麻煩,我不明白爲什麼這個東西不行。我需要爲每個數組的值做一個API請求,如果我看着我的控制檯的JavaScript,請求被服務,但我需要在請求內的經度和緯度值。問題是,API請求外我有4個值(數組的每個元素2拉特和長),並在API請求中找到只有最後兩個緯度和長,爲什麼呢?這似乎真的沒有任何意義,我不知道哪裏出了問題可能be.Here是代碼循環內的API請求有問題

var luoghi = {"city":[ 
        { "lat":"45.46" , "lng":"9.19" , "name":"Milano" }, 
        { "lat":"41.12" , "lng":"16.86" , "name":"Bari" } 
      ]}; 
var arr=[]; 
for(var i in luoghi.city){ 
lat = luoghi.city[i].lat; 
lng= luoghi.city[i].lng; 

console.log("Before API request "+lat+" "+lng);//here i have the right 4 values 

var wUnderAPI = "http://api.wunderground.com/api/"+API_WU+"/forecast/q/"+lat+","+lng+".json?callback=?"; 
$.getJSON(wUnderAPI, {format: "json"}).done(function(data) { 
    if(typeof data['forecast']['simpleforecast']['forecastday'] != 'undefined'){ // controllo esito richiesta json 
      console.log(" Inside the request "+lat+" "+lng); //here just the bari lat & lng 
    } 
}); 
} 

的API_WU是我的私有API KEY,但因爲它是對於非商業用途,任何人都可以從網站獲得一個。希望我的問題很清楚,因爲這是一個問題時間甚至很難解釋:)預先感謝。

回答

0

您的done函數引用之前定義的lat,lng,因爲它是異步的,例如,它可能需要一些時間才能返回,並且不會阻止循環中的腳本,它會始終爲您提供最後定義的值,因爲它最有可能僅在處理完所有其他值後才返回。您需要將正確的數據提供給done函數中的回調函數。

嘗試傳遞latlng作爲參數傳遞給done

$.getJSON(wUnderAPI, {format: "json"}).done(function(data, lat, lng) { 
    if(typeof data['forecast']['simpleforecast']['forecastday'] != 'undefined'){ // controllo esito richiesta json 
      console.log(" Inside the request "+lat+" "+lng); //here just the bari lat & lng 
    } 
}); 
+0

我剛剛試過了,現在它不打印我什麼可讀,控制檯輸出爲「在請求中成功的翻譯:」所以lat和lng沒有數字值:/ @RobSchmuecker – Mirko

+0

@ yee379嗨,我見過你在這裏回答了類似的問題[link](http://stackoverflow.com/questions/3430380/how-can-i-pass -parameters-to-a-jquery-getjson-callback-method)但我無法理解在我的情況下該怎麼做,請你幫助我嗎?在此先感謝:) – Mirko