gpt4 book ai didi

javascript - 将 Google API 请求保存为 Javascript 对象

转载 作者:行者123 更新时间:2023-12-03 05:18:18 25 4
gpt4 key购买 nike

我真的很努力地执行我确信是一项相当简单的任务。我正在使用 Google Sheets API 从电子表格中提取数据。我想将数据存储在 Javascript 对象中。

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

我从 https://developers.google.com/api-client-library/javascript/start/start-js 获取了我的代码模板和 https://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

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

最佳答案

使用回调函数和全局变量。这是该函数发出异步 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?

关于javascript - 将 Google API 请求保存为 Javascript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41514329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com