0

我是一个业余程序员,在一个小项目上遇到了困难。我想从 Google 电子表格中获取数据,修改数据并制作 Google Chart(使用 google chart api)。

下面的代码在 Firefox 中完美运行,但 Chrome 和 IE 不允许 dataTable 超出 handleQueryResponse(e) 函数的范围。我的第一个想法是从 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;
 }
4

2 回答 2

3

调用异步函数 ( queryTrip.send)的函数不能返回取决于该异步函数调用结果的数据,也不能以其他方式使用该数据。

该数据在回调函数内部可用,以及随后该回调调用的任何其他函数。

于 2012-05-09T15:45:46.843 回答
0

as felix mentioned, it's probably asynchronous, meaning that variable no longer exists by the time the handleQueryResponse gets run because it's not run instantly within the scope of the function getDataTable.

You could put the variable for dataTable outside that scope ( into global scope ) than the handleQueryResponse would be able to write to it.

However you will want to initiate any functions that need to run after the dataTable is ready from within the handleQueryResponse function. Best course of action might be to use some sort of event driven handling for after the dataTable is ready.

于 2012-05-09T15:34:17.760 回答