2015-05-29 103 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