我想创建一个简单的函数来读取一些json,做一些简单的处理,然后返回一个数组。
我目前有以下代码。但是,该函数始终返回[]。
如果我将temps移动到全局范围,它首先返回[],然后第二次调用它被添加数据,第三次调用它时它的长度加倍等。
function getTempData() {
var temps = [];
$.getJSON('temp.json', function(data) {
data = data.observations.data;
for(var i = 0; i < data.length; i++) {
year = parseInt(data[i].aifstime_utc.substr(0, 4));
month = parseInt(data[i].aifstime_utc.substr(4, 2));
day = parseInt(data[i].aifstime_utc.substr(6, 2));
hour = parseInt(data[i].aifstime_utc.substr(8, 2));
min = parseInt(data[i].aifstime_utc.substr(10, 4));
time = Date.UTC(year, month, day, hour, min);
temps.push([time, data[i].air_temp]);
}
});
return temps;
}
看看其他一些问题,看来这可能与异步有关吗?有没有办法让它同步加载,我想在高图中绘制数据。
答案 0 :(得分:1)
dakait几乎就在那里,因为在函数处理数据被调用之前,函数返回的ajax调用的异步性质。请考虑以下示例:
function test(){
var done=false;
setTimeout(function(){
done=true;
},500);
return done;
};
alert(test());//will say false
在您的代码中,您需要3个功能: 1)调用getTempData 2)从服务器获取数据 3)处理数据
function getTempData() {
var temps = [];
// 2) fetch the data
$.getJSON('temp.json',
function(data) {
// 3) process the data
data = data.observations.data;
for(var i = 0; i < data.length; i++) {
year = parseInt(data[i].aifstime_utc.substr(0, 4));
month = parseInt(data[i].aifstime_utc.substr(4, 2));
day = parseInt(data[i].aifstime_utc.substr(6, 2));
hour = parseInt(data[i].aifstime_utc.substr(8, 2));
min = parseInt(data[i].aifstime_utc.substr(10, 4));
time = Date.UTC(year, month, day, hour, min);
temps.push([time, data[i].air_temp]);
}
processTempData(temps);
});
//return temps;//this line executed immediately after $.getJSON is called
// but before function 2) has been called
}
1)
function callgetTempData(){
//...
getTempData();
// no use processing anything here since the ajax call is not finished yet
// asynchronous means that js will not wait until it's done.
// I would not advice using synchronous
}
2) // further process data
function processTempData(theData){
// do something with the data here
}
在具有大量ajax调用的应用程序中,您可以考虑使用中介模式:
Good pattern to use for multiple xmlhttprequests used by different processes