将Google API请求另存为Javascript对象

时间:2017-01-06 21:05:04

标签: javascript google-api

我真的很难表现出我确信这是一项相当简单的任务。我使用Google表格API从电子表格中提取数据。我想将数据存储在Javascript对象中。

到目前为止,我能够成功地从API请求数据,我知道它正在工作,因为我可以将它打印到控制台。但我一直在尝试并且未能将这些相同的数据存储为对象。

我从https://developers.google.com/api-client-library/javascript/start/start-jshttps://developers.google.com/sheets/api/samples/reading抓取了我的代码模板。

这是我目前的代码:

<script src="https://apis.google.com/js/api.js"></script> 
<script> 
function start() {
    // 2. Initialize the JavaScript client library.
    gapi.client.init({
      'apiKey': 'key',
      // clientId and scope are optional if auth is not required.
      'clientId': 'client_id',
      'scope': 'profile'}).then(function() {
        // 3. Make the request
        return gapi.client.request({
          'path': 'https://sheets.googleapis.com/v4/spreadsheets/sheet_id/values/Sheet3'});
        }).then(function(response){
            console.log(response.result);
   }); 
};
// 1. Load the JavaScript client library. 
gapi.load('client', start);
</script>

它成功打印到日志: enter image description here

但我不知道如何存储这些数据并在以后访问它。我很感激任何帮助!

1 个答案:

答案 0 :(得分:1)

使用回调函数和全局变量。这是函数发出异步XHR请求以来的唯一方法。

var results; // global variable. Only accessed after XHR returned response. 
function start() {
    // 2. Initialize the JavaScript client library.
    gapi.client.init({
      'apiKey': 'key',
      // clientId and scope are optional if auth is not required.
      'clientId': 'client_id',
      'scope': 'profile'}).then(function() {
        // 3. Make the request
        return gapi.client.request({
          'path': 'https://sheets.googleapis.com/v4/spreadsheets/sheet_id/values/Sheet3'});
        }).then(function(response){
            results = response; // update global variable, and then call your callback function
            onResultsSuccess(results); // response will also work.
   }); 
};
// 1. Load the JavaScript client library. 
gapi.load('client', start);

onResultsSuccess(data){
    console.log(data.result);
    // more code.
}

进一步阅读:How do I return the response from an asynchronous call?