我仍在学习网络开发,因此我的业余行话,但我确实需要能够从 Google 工作表中提取一些数据,并在 Javascript 动画 Canvas 对象中直观地表示它。
不幸的是,像往常一样,Google Sheets API 文档并不是为像我这样的人编写的!基本的 GETer 应用程序在我的本地 Python 服务器上运行得很好,但现在抛出一个错误,因为我在托管网站上测试了它。我认为这是一个 JSONP 问题,因为错误以“X-Frame-Options 拒绝加载”开头,但文档中似乎没有提及如何以 JSONP 形式发出请求。我已将电子表格公开,因此不需要身份验证步骤。
这是代码,删除了 ID 等:
<script>
var CLIENT_ID = 'my_client_id';
var SCOPES = ["https://www.googleapis.com/auth/spreadsheets.readonly"];
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES.join(' '),
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* @param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
loadSheetsApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
console.log('nope');
}
}
/**
/**
* Load Sheets API client library.
*/
function loadSheetsApi() {
var discoveryUrl =
'https://sheets.googleapis.com/$discovery/rest?version=v4';
gapi.client.load(discoveryUrl).then(trackDonations);
}
/**
* Print values in the donations column
*/
function trackDonations() {
gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: 'my_sheet_id',
range: 'Form Responses 1!C2:C',
}).then(function(response) {
var range = response.result;
if (range.values.length > 0) {
console.log(range.values);
$('.sum').text(range.values[range.values.length-1]);
} else {
prompt('No data found.');
}
}, function(response) {
prompt('Error: ' + response.result.error.message);
});
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
也许我错过了一些愚蠢的东西,但非常感谢您的指导!谢谢!
最佳答案
如果您使用电子表格,那么使用 AppsScript 可能会更容易。
从电子表格中,转到“工具”>“脚本编辑器”。本页展示如何将数据加载到数组中 https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#getDataRange()然后将其作为 jsonp https://developers.google.com/apps-script/guide/content#serving_jsonp_in_web_pages如果您随后“部署为 Web 应用程序”(云图标),他们将为您提供一个在代码中引用的 URL。
它与使用其余 api 类似,但可以让您更好地控制响应的工作方式。
关于javascript - 无法理解如何实现 Google Sheets API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40135531/