【发布时间】:2013-12-25 11:53:59
【问题描述】:
我编写了以下函数,该函数从 url 获取 json 数据。
function getWeatherDataForCities(cityArray){
var arrAllrecords = [];
var toDaysTimestamp = Math.round((new Date()).getTime() / 1000) - (24*60*60);
for(var i in cityArray){
for(var j=1; j<=2; j++){
var jsonurl = "http://api.openweathermap.org/data/2.5/history/city?q="+cityArray[i]+"&dt="+toDaysTimestamp;
$.ajax({
url: jsonurl,
dataType: "jsonp",
mimeType: "textPlain",
crossDomain: true,
contentType: "application/json; charset=utf-8",
success: function(data){
arrAllrecords[j]["cityName"] = data.list[0].city.name;
arrAllrecords[j]["weather"] = data.list[0].weather[0].description;
} });
toDaysTimestamp = toDaysTimestamp - (24*60*60);
}
}
return arrAllrecords; //returning arrAllrecords
}
$(document ).ready(function() {
var cityArray = new Array();
cityArray[0] = "pune";
var arrAllRecords = getWeatherDataForCities(cityArray);
//Print All records returned by getWeatherDataForCities(cityArray);
});
我在上面的代码中写了一些 cmets。我调用了getWeatherDataForCitiesfunction,它返回了来自url的所有记录。我在函数中声明了getWeatherDataForCitiesarray。我想将所有返回的记录添加到那个数组。我已经按照上面的方法进行了尝试,但没有任何内容进入array。
在控制台中显示 j 和 arrAllrecords 未定义。
如何从回调函数中获取数组中的所有记录?
我们将非常感谢您的回复
【问题讨论】:
标签: javascript jsonp jquery-callback