在GitHub页面中使用基本的Google Sheets JavaScript脚本涉及到几个步骤,包括设置Google Sheets API、获取API密钥、编写脚本以及将其嵌入到GitHub页面中。以下是详细的步骤和相关概念:
以下是一个简单的示例,展示如何使用Google Sheets API读取数据并在网页上显示:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Google Sheets Example</title>
</head>
<body>
<div id="data"></div>
<script>
function initClient() {
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
'discoveryDocs': ['https://sheets.googleapis.com/$discovery/rest?version=v4'],
'clientId': 'YOUR_CLIENT_ID',
'scope': 'https://www.googleapis.com/auth/spreadsheets.readonly'
}).then(function () {
return gapi.client.sheets.spreadsheets.values.get({
'spreadsheetId': 'YOUR_SPREADSHEET_ID',
'range': 'Sheet1!A1:D10'
});
}).then(function (response) {
var rows = response.result.values;
if (rows) {
var dataDiv = document.getElementById('data');
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var rowDiv = document.createElement('div');
rowDiv.innerHTML = row.join(', ');
dataDiv.appendChild(rowDiv);
}
} else {
dataDiv.innerHTML = "No data found.";
}
}, function (error) {
console.log('Error: ' + error);
});
}
function loadClient() {
gapi.load('client:auth2', initClient);
}
</script>
<script src="https://apis.google.com/js/platform.js?onload=loadClient" async defer></script>
</body>
</html>
将上述HTML文件上传到你的GitHub仓库,并在GitHub Pages上部署。
原因: 可能是由于API密钥不正确或权限设置不正确。
解决方法: 检查API密钥是否正确,并确保在Google Cloud Console中为你的项目启用了正确的权限。
原因: 直接在客户端代码中暴露API密钥可能会导致安全风险。
解决方法: 使用服务器端代理来处理API请求,或者使用OAuth 2.0进行用户认证。
通过以上步骤和资源,你应该能够在GitHub页面中成功使用基本的Google Sheets JavaScript脚本。
领取专属 10元无门槛券
手把手带您无忧上云