2013-03-11 19 views
0

我想創建一個簡單的函數來讀取一些json,做一些簡單的處理,並返回一個數組作爲結果。變量未在Javascript中使用嵌套函數和getJSON進行更新

目前,我有下面的代碼。但是,該函數總是返回[]。

如果我移動臨時工到全球範圍內時,它首先返回[],然後它被稱爲數據的第二時間被添加,並且它被稱爲第三時間是兩倍的長度等

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

如果你console.log(數據)會發生什麼?它實際上是否包含任何數據? – kennypu 2013-03-11 06:25:57

+0

您可以使AJAX調用同步,但這是一個非常糟糕的主意。查看AJAX回調如何工作的已有答案,已經解釋了數百萬次。 (並停止創建全局變量。) – DCoder 2013-03-11 06:28:02

回答

1

dakait幾乎沒有,因爲AJAX的asynchronyous性質調用函數處理數據已經調用之前你的函數返回。請看下面的例子:

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 
} 

在應用程序與大量的阿賈克斯呼叫,這是您可能考慮使用介體模式的過程的一部分:

Good pattern to use for multiple xmlhttprequests used by different processes