我是一個業餘程序員,在一個小項目中很難過。我想從Google電子表格中獲取數據,修改數據並製作Google圖表(使用google圖表API)。變量的Javascript範圍無法正常工作
下面的代碼在Firefox中完美工作,但Chrome和IE不允許handleQueryResponse(e)函數範圍之外的dataTable。我的第一個想法是從handleQueryResponse(e)函數返回dataTable,但在函數內部調用(.send())。
任何幫助將不勝感激。
function getDataTable(link) {
var dataTable= new google.visualization.DataTable();
var queryTrip = new google.visualization.Query(link);
queryTrip.send(handleQueryResponse);
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
dataTable = response.getDataTable();
// I can verify this has the data through debugging in Chrome
}
// Outside of the function handleQueryResponse the dataTable is gone
return dataTable;
}
我假設'queryTrip.send'是異步的。在這種情況下,在你的函數被回調設置之前,你會返回'dataTable'。那就是'return dataTable;'在'dataTable = response.getDataTable();'之前執行。如果涉及異步函數調用,則不能從函數返回值。你應該讓'getDataTable'接受一個回調,你可以調用結果準備好並將它傳遞給回調函數。 –
「允許」在這種情況下沒有意義。所有瀏覽器都允許在任何地方定義變量。請更具體一點:你在某處遇到錯誤嗎?如果是這樣,告訴我們整個錯誤信息! –
@JoshMein在Javascript中的其他函數中聲明函數是完全正常的。 – Alnitak