2017-01-06 21 views
0

我非常努力地執行我確信的任務,這是一項相當簡單的任務。我正在使用Google Sheets API從電子表格中提取數據。我想將數據存儲在一個Javascript對象中。將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

但我不知道如何來存儲這些數據,並稍後訪問它。我會很感激任何幫助!

+2

您將需要一個回調函數和一個預定義的全局變量。 –

回答

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?

+0

非常感謝!這工作,我欣賞額外的參考。 – ZachTurn

+0

@ZachTurn,你最受歡迎。 :)快樂的編碼 –