点击按钮向Google Apps Script传值并写入Google Sheet问题求助
问题排查与代码修正
前端代码核心错误
- 未获取元素实际值:直接把DOM元素对象存入
data,而非元素的内容。需取文本框的value和计数器的textContent。 - fetch语法错误:请求配置对象被错误放在URL括号外,导致请求未使用POST方法和正确请求头。
- 缺少jQuery依赖:增减计数器函数用了
$(jQuery),但页面未引入jQuery库,会导致控制台报错,计数器功能失效。 - 未处理请求响应/错误:没有添加
then/catch逻辑,无法调试请求是否成功。
修正后的前端代码
<!DOCTYPE html> <html> <head> <title>Counter and text field</title> <!-- 引入jQuery,解决计数器函数依赖问题 --> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <h2> Major: <span class="counter" id="counter18">0</span></h2> <button class="button-plus_minus" onclick="incrementCounter(18)">+</button> <button class="button-plus_minus" onclick="decrementCounter(18)">-</button> <textarea cols="20" rows="1" class="text-field_input" name="information" id="information" autocomplete="off" placeholder="Write information"></textarea> <button onclick="Send()">Send</button> </body> <script> function incrementCounter(counterNumber) { let counter = parseInt($('#counter' + counterNumber).text()); counter++; $('#counter' + counterNumber).text(counter); } function decrementCounter(counterNumber) { let counter = parseInt($('#counter' + counterNumber).text()); // 可选:防止计数器变为负数 if (counter > 0) { counter--; $('#counter' + counterNumber).text(counter); } } async function Send() { // 获取元素的实际值 var information = document.getElementById('information').value; var counter18value = document.getElementById('counter18').textContent; var data = { information: information, counter18value: counter18value }; try { const response = await fetch('https://script.google.com/macros/s/XXX/exec', { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); const result = await response.text(); console.log('提交成功:', result); alert('数据已提交'); // 提交后清空文本框并重置计数器 document.getElementById('information').value = ''; document.getElementById('counter18').textContent = '0'; } catch (error) { console.error('提交失败:', error); alert('提交失败,请查看控制台日志'); } } </script> </html>
Google Apps Script 后端代码
打开目标Google Sheets,点击菜单栏「扩展程序」→「Apps脚本」,替换默认代码为:
function doPost(e) { try { // 解析前端发送的JSON数据 const data = JSON.parse(e.postData.contents); const information = data.information; const counterValue = data.counter18value; // 获取当前Sheet(可修改为你的Sheet名称) const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet(); // 写入数据,附带时间戳 sheet.appendRow([new Date(), information, counterValue]); // 返回成功响应 return ContentService.createTextOutput(JSON.stringify({status: 'success', message: '数据已写入'})) .setMimeType(ContentService.MimeType.JSON); } catch (error) { // 返回错误响应 return ContentService.createTextOutput(JSON.stringify({status: 'error', message: error.toString()})) .setMimeType(ContentService.MimeType.JSON); } }
部署注意事项
- 在Apps脚本编辑器中,点击「部署」→「新部署」。
- 类型选择「Web应用」,执行权限选「我」,访问权限选「任何人,甚至匿名」。
- 点击部署,复制生成的Web应用URL,替换前端代码中的
XXX部分。
内容的提问来源于stack exchange,提问作者Рубен Агасян
相关产品推荐
相关产品推荐

