检查了半天多了,我现在脑子一片空白!我不知道我在哪里失踪了还是什么?请帮助我。我的代码如下。
这里有一个更详细的方法可以帮助您回到代码的正轨。gs:
function readRecords() {
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
const data = sheet.getDataRange().getValues();
const headers = data[0];
return data.slice(1).map(row => {
return headers.reduce((record, header, idx) => ({ ...record, [header]: row[idx] }), {});
});
}
我的 .html 代码如下:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<title>Show Records</title>
</head>
<body>
<div id="recordsContainer"></div>
<script>
function displayRecords(records) {
const container = document.getElementById('recordsContainer');
container.innerHTML = '';
if (records.length === 0) {
container.innerHTML = '<p>No records found.</p>';
return;
}
const table = document.createElement('table');
table.classList.add('table');
const thead = table.createTHead();
const row = thead.insertRow();
Object.keys(records[0]).forEach(header => {
const th = document.createElement('th');
th.textContent = header;
row.appendChild(th);
});
const tbody = table.createTBody();
records.forEach(record => {
const row = tbody.insertRow();
Object.values(record).forEach(value => {
const td = row.insertCell();
td.textContent = value;
});
});
container.appendChild(table);
}
function fetchRecords() {
google.script.run.withSuccessHandler(displayRecords).readRecords();
}
window.onload = fetchRecords;
</script>
</body>
</html>
我的问题和缺失在哪里,请帮助我。
。
function displayRecords(records) {
const container = document.getElementById('recordsContainer');
container.innerHTML = '';
if (records.length === 0) {
container.innerHTML = '<p>No records found.</p>';
return;
}
const table = document.createElement('table');
table.classList.add('table');
const thead = table.createTHead();
const row = thead.insertRow();
Object.keys(records[0]).forEach(header => {
const th = document.createElement('th');
th.textContent = header;
row.appendChild(th);
});
const tbody = table.createTBody();
records.forEach(record => {
const row = tbody.insertRow();
Object.values(record).forEach(value => {
const td = row.insertCell();
td.textContent = value;
});
const actionCell = row.insertCell();
actionCell.innerHTML = `
<button class="btn btn-info" onclick="editRecord(${record.ID})">Edit</button>
<button class="btn btn-danger" onclick="deleteRecord(${record.ID})">Delete</button>
`;
});
console.log({records})
container.appendChild(table);
}
您可以像这样获取谷歌电子表格数据,需要添加您的电子表格ID,范围和apiKey。
async function fetchSheetData() {
const url = `https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/${range}? key=${apiKey}`;
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
catch (error) {
console.error("Error fetching data:", error);
}
}