You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

表单提交至Google Sheets失败求助(含打字速度测试功能)

问题排查与修复方案

核心问题梳理

你的代码存在多个关键问题,导致无法正常运行:

  • HTML文档声明错误:第一行!DOCTYPE html>缺少开头的<,浏览器无法正确识别文档类型。
  • 打字测速逻辑阻塞浏览器:measureTypingSpeed里的while循环是死循环,JS单线程特性会让浏览器完全卡住,用户根本无法输入内容。
  • 测速目标文本不匹配:页面显示的是随机生成的句子,但测速函数里用固定文本做对比,永远无法触发结束条件。
  • Google Sheets数据存储逻辑错误:前端JS没有内置GoogleSheetsAPI对象,浏览器端无法直接操作Google Sheets,必须通过Google Apps Script搭建中间服务。
  • 表单提交事件逻辑错误:onsubmit里用了位运算符&,应该用逻辑与&&,且原函数执行顺序和返回值会导致表单提交异常。

修复后的完整代码

1. HTML代码(托管在GitHub)

<!DOCTYPE html>
<html>
<head>
<title>志愿者招募表单</title>
<style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f1f1f1;
    }
  
    h1 {
      text-align: center;
      color: #333;
    }
  
    form {
      max-width: 500px;
      margin: auto;
      padding: 20px;
      background-color: #fff;
      border: 1px solid #ddd;
    }
  
    p {
      margin-top: 10px;
    }
  
    input[type=text] {
      width: 100%;
      padding: 12px;
      box-sizing: border-box;
    }
  
    input[type=submit] {
      background-color: #4CAF50;
      color: white;
      padding: 12px 20px;
      border: none;
      cursor: pointer;
    }
  
    input[type=submit]:hover {
      background-color: #45a049;
    }

    .sentence-block {
      background: #f5f5f5;
      padding: 10px;
      border-radius: 4px;
      margin-bottom: 10px;
    }
  </style>
  
</head>
<body>
<h1>志愿者招募表单</h1>

<img src="logo.png" alt="Logo" width="200" height="200">
<form id="recruitmentForm">
<p>1. 姓名: <input type="text" name="name" required></p>
<p>2. 地址: <input type="text" name="address" required></p>
<p>3. 班级: <input type="text" name="class" required></p>
<p>4. 组别: <input type="text" name="section" required></p>
<p>5. 打字速度测试:
  <div class="sentence-block" id="targetSentences"></div>
  <input type="text" name="typing_test" id="typingInput" required></p>

<input type="submit" value="提交">
</form> 

<script>
// 初始化随机显示的句子
const sentences = [
  "The quick brown fox jumps over the lazy dog.",
  "She sells seashells by the seashore.",
  "The rain in Spain stays mainly in the plain.",
  "I saw Susie sitting in a shoe shine shop.",
  "How can a clam cram in a clean cream can?",
  "A proper copper coffee pot."
];

let targetText = '';
let startTime = null;

// 生成随机句子并显示
function generateRandomSentences() {
  const randomSentences = [];
  for (let i = 0; i < 6; i++) {
    const randomIndex = Math.floor(Math.random() * sentences.length);
    randomSentences.push(sentences[randomIndex]);
  }
  targetText = randomSentences.join(' ');
  document.getElementById('targetSentences').innerHTML = randomSentences.join('<br>');
}

// 监听输入框开始输入事件
document.getElementById('typingInput').addEventListener('focus', () => {
  if (!startTime) {
    startTime = Date.now();
  }
});

// 表单提交时计算打字速度并提交数据
document.getElementById('recruitmentForm').addEventListener('submit', async (e) => {
  e.preventDefault();
  
  // 计算打字速度
  const inputValue = document.getElementById('typingInput').value.trim();
  if (inputValue !== targetText) {
    alert('输入内容与目标句子不匹配,请重新输入!');
    return;
  }

  const endTime = Date.now();
  const elapsedTime = (endTime - startTime) / 1000; // 转换为秒
  const wordCount = targetText.split(' ').length;
  const typingSpeed = Math.round((wordCount / elapsedTime) * 60);
  alert(`你的打字速度是: ${typingSpeed} 字/分钟`);

  // 收集表单数据
  const formData = new FormData(e.target);
  formData.append('typing_speed', typingSpeed);

  // 提交到Google Apps Script Web App(替换成你自己的Web App地址)
  try {
    const response = await fetch('https://script.google.com/macros/s/你的WebAppID/exec', {
      method: 'POST',
      body: formData
    });
    const result = await response.text();
    if (result === 'Success') {
      alert('表单提交成功!');
      e.target.reset();
      startTime = null;
      generateRandomSentences();
    } else {
      alert('提交失败,请重试!');
    }
  } catch (error) {
    alert('网络错误,请检查连接!');
    console.error(error);
  }
});

// 页面加载时生成随机句子
window.onload = generateRandomSentences;
</script>
</body>
</html>

2. Google Apps Script代码(搭建数据存储服务)

  1. 打开Google Apps Script,创建新的项目
  2. 替换默认代码为以下内容:
const SPREADSHEET_ID = '你的Google Sheets文档ID'; // 从你的表格URL中提取,比如URL里的1zVvU0_VzrjmcOl33E4BOKhlsGt26cQQVnpV8R4AJvSw

function doPost(e) {
  try {
    const sheet = SpreadsheetApp.openById(SPREADSHEET_ID).getSheetByName('Sheet1'); // 确保表格有Sheet1,或者改成你的工作表名称
    const data = [
      new Date(), // 提交时间
      e.parameter.name,
      e.parameter.address,
      e.parameter.class,
      e.parameter.section,
      e.parameter.typing_speed,
      e.parameter.typing_test
    ];
    sheet.appendRow(data);
    return ContentService.createTextOutput('Success').setMimeType(ContentService.MimeType.TEXT);
  } catch (error) {
    console.error(error);
    return ContentService.createTextOutput('Error').setMimeType(ContentService.MimeType.TEXT);
  }
}
  1. 部署为Web App:
    • 点击右上角「部署」→「新部署」
    • 类型选择「Web应用」
    • 执行权限选择「我」
    • 谁可以访问选择「任何人,甚至匿名」(根据需求调整,公开表单选这个)
    • 点击部署,复制生成的Web App URL,替换到HTML代码中的fetch地址

关键修复说明

  1. 修复文档声明:补全<!DOCTYPE html>,确保浏览器正确渲染页面
  2. 重构测速逻辑:去掉死循环,改用focus事件记录开始时间,提交时对比输入内容和目标文本,计算速度
  3. 统一目标文本:页面显示的随机句子和测速用的文本保持一致,避免匹配失败
  4. Google Sheets数据存储:通过Google Apps Script搭建Web App作为中间层,解决前端跨域和权限问题,实现数据提交到表格
  5. 优化表单提交:用addEventListener绑定提交事件,阻止默认提交行为,异步处理数据提交

内容的提问来源于stack exchange,提问作者noob20221215

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 03:10:37