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

从Google Sheets获取数据失败求助(含前端与脚本代码)

问题:无法从Google Sheets读取数据实现重复提交校验

我正在开发一个表单,用户提交的数据可以写入Google Sheets,但无法从中读取邮箱和ID数据来对比当前表单数据、判断是否为重复提交并拒绝。更换新的脚本执行URL后问题仍未解决。

前端代码

const scriptURL = 'your script here';
const [existingFormData, setExistingFormData] = useState([]); // 存储Google表格中已有表单数据的状态

// 组件挂载时获取Google表格中的已有数据
useEffect(() => {
  const fetchData = async () => {
    try {
      // 从Google Apps Script获取数据
      console.log('正在从Google表格获取数据...');
      const response = await fetch(scriptURL);
      console.log('响应结果:', response);

      if (!response.ok) {
        throw new Error(`HTTP请求错误!状态码: ${response.status}`);
      }

      const contentType = response.headers.get('content-type');
      if (!contentType || !contentType.includes('application/json')) {
        throw new TypeError('未获取到JSON格式的数据!');
      }

      // 解析响应中的JSON数据
      const data = await response.json();
      console.log('获取到的数据:', data);
      
      // 将数据存入状态
      setExistingFormData(data);
    } catch (error) {
      console.error('获取已有数据时出错:', error);
    }
  };

  // 组件挂载时调用获取数据的函数
  fetchData();
}, []); // 空依赖数组确保仅在组件挂载后执行一次

Google Apps Script代码

const sheetName = 'BHD';
const scriptProp = PropertiesService.getScriptProperties();

function doGet(e) {
  return HtmlService.createHtmlOutput('Success!')
    .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

function initialSetup() {
  const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  scriptProp.setProperty('key', activeSpreadsheet.getId());
}

function doPost(e) {
  Logger.log('doPost函数正在执行。');
  const lock = LockService.getScriptLock();
  lock.tryLock(10000);

  try {
    const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
    const sheet = doc.getSheetByName(sheetName);

    const data = sheet.getDataRange().getValues();
    Logger.log(data);

    // 初始化存储邮箱和ID的数组
    const studentEmailArray = [];
    const studentIDArray = [];

    // 遍历二维数据列表
    for (let i = 0; i < data.length; i++) {
      // 获取每行中的邮箱和ID
      const studentEmail = data[i][2]; // 目标为每行第三个元素(索引2)
      const studentID = String(data[i][3]); // 将ID从科学计数法转为字符串
      
      // 日志记录值用于验证
      Logger.log(studentEmail);
      Logger.log(studentID);

      // 将值存入数组
      studentEmailArray.push(studentEmail);
      studentIDArray.push(studentID);
    }

    // 返回包含数组的对象
    return createTextOutputWithCors(JSON.stringify({ 'result': 'success', 'studentEmailArray': studentEmailArray, 'studentIDArray': studentIDArray }));

  } catch (error) {
    Logger.log('打开表格时出错:', error.message);
    return createTextOutputWithCors({ 'result': 'error', 'error': error.message });
  } finally {
    lock.releaseLock();
  }
}

function createTextOutputWithCors(data) {
  return ContentService.createTextOutput(data).setMimeType(ContentService.MimeType.JSON);
}

内容的提问来源于stack exchange,提问作者e.a.2.6.9

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 14:30:00