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

Google Apps Script调用成功但HTML接收数据为null求助

谷歌表格侧边栏接收Apps Script返回数据为null的排查与解决

问题背景

我开发的谷歌表格侧边栏功能可按案件编号筛选记录,当前遇到以下异常:

  • 侧边栏正常打开,搜索框可触发getInfoById()调用
  • Apps Script执行日志显示:传入的案件编号正确、表格数据完整、匹配到目标行
  • HTML控制台日志显示接收的数据为null

已尝试的操作:

  • 重构代码,不筛选直接返回全部数据
  • 手动测试Apps Script参数
  • 此前已实现HTML调用Apps Script写入数据的功能
  • 代码基于同事在其他数据集上的实现修改而来

相关代码

HTML(JavaScript部分)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <div>
      <label for="idInput">ID:</label>
      <input type="number" id="idInput">
      <button onclick="getInfo()">Search</button>
    </div>
    <div id="info"></div>
    <script>
  function getInfo() {
    const searchId = document.getElementById('idInput').value;
    google.script.run.withSuccessHandler(function(data) {
      console.log('Data received:', data);
      const infoDiv = document.getElementById('info');
      infoDiv.innerHTML = '';
      if (data && data.length > 0) {
        data.forEach(function(row, index) {
          const recordHtml = `School: ${row[0]}<br>Name: ${row[1]}<br>ID: ${row[2]}<br><button onclick="editRecord(${index}, '${row[2]}')">Edit</button><br><br>`;
          infoDiv.innerHTML += recordHtml;
        });
      } else {
        infoDiv.innerHTML = 'No matching records found.';
      }
    }).withFailureHandler(function(error) {
      console.error('Error:', error);
      const infoDiv = document.getElementById('info');
      infoDiv.innerHTML = 'Error occurred while retrieving data.';
    }).getInfoById(searchId);
  }

 function editRecord(index, id) {
    const columnChoice = window.prompt("Choose column to edit (1 for School, 2 for Name, 3 for ID):");
    let newValue = window.prompt("Enter new value:");
    
    if (!newValue || !columnChoice || isNaN(columnChoice) || columnChoice < 1 || columnChoice > 3) {
      alert("Invalid input. Please try again.");
      return;
    }
    
    google.script.run.withSuccessHandler(function() {
      alert("Record updated successfully.");
      getInfo();
    }).updateRecordById(id, columnChoice, newValue);
  }
</script>
  </body>
</html>

Apps Script代码

function getInfoById(searchId) {
  Logger.log(searchId)
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
  const range = sheet.getDataRange();
  const values = range.getValues();
  Logger.log(values)
  const matchedRows = [];
  for (let i = 1; i < values.length; i++) {
    if (values[i][0].toString() === String(searchId)) {
      matchedRows.push([values[i][0], values[i][1], values[i][5]]);
    }
  }
  Logger.log(matchedRows)
  return matchedRows;
}

排查与解决方案

1. 验证返回数据的可序列化性

google.script.run仅支持返回可JSON序列化的数据(如字符串、数字、数组、普通对象),若返回内容包含不可序列化对象(如Date、Spreadsheet服务对象),会导致前端接收null。

在getInfoById末尾添加日志,验证数据是否能正常序列化:

Logger.log(JSON.stringify(matchedRows)); // 检查日志输出是否为有效JSON

若输出异常,需清理返回数据中的不可序列化内容。

2. 统一参数类型匹配

HTML中input[type="number"]的value为字符串类型,而表格中存储的案件编号可能是数字类型,字符串与数字的严格相等判断可能隐藏问题。

修改HTML的参数传递逻辑,转为数字类型:

// 在getInfo函数中修改
const searchId = parseInt(document.getElementById('idInput').value, 10);

同时修改Apps Script中的判断逻辑,避免类型转换:

// 在getInfoById的循环中修改
if (values[i][0] === searchId) {

3. 检查函数执行的完整性

确保getInfoById函数无未捕获错误导致提前退出。例如,若表格中某行的values[i][0]为undefined,调用toString()会报错,导致函数终止返回null。

添加错误捕获逻辑:

function getInfoById(searchId) {
  try {
    Logger.log(searchId)
    const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1');
    if (!sheet) throw new Error('Sheet1 not found');
    const range = sheet.getDataRange();
    const values = range.getValues();
    Logger.log(values)
    const matchedRows = [];
    for (let i = 1; i < values.length; i++) {
      // 跳过空行或无效数据行
      if (!values[i][0]) continue;
      if (values[i][0].toString() === String(searchId)) {
        matchedRows.push([values[i][0], values[i][1], values[i][5]]);
      }
    }
    Logger.log(matchedRows)
    Logger.log(JSON.stringify(matchedRows));
    return matchedRows;
  } catch (e) {
    Logger.log('Function error: ' + e.message);
    throw e; // 抛出错误让failureHandler捕获
  }
}

4. 重新授权脚本权限

若脚本权限过期或未正确授权,可能导致google.script.run调用异常。手动运行一次getInfoById函数(传入测试参数),触发谷歌的授权流程,确保权限正常。

5. 测试简化返回值

暂时修改getInfoById直接返回固定测试数据,验证前端是否能正常接收:

function getInfoById(searchId) {
  return [["Test School", "Test Name", "12345"]];
}

若前端能收到该数据,说明问题出在原数据匹配逻辑或表格数据上;若仍为null,需检查脚本部署设置或浏览器缓存(尝试清空缓存后重新打开侧边栏)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 21:22:46