2017-01-06 4 views
0

私は本当に簡単な作業であると確信しています。私はGoogleスプレッドシートからデータを抽出するためにGoogleスプレッドシートAPIを使用しています。私は、Javascriptオブジェクトにデータを格納したい。JavascriptオブジェクトとしてGoogle APIリクエストを保存する

これまでのところ、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、あなたは一番歓迎です。 :)ハッピーコーディング –

関連する問題