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

如何编写doGet(e)函数获取名称/值数组?求doPost等价实现

用doGet(e)实现Google表格追加行的等价代码

doGet(e)和doPost(e)的核心区别在于请求数据的获取方式:POST通过请求体传递数据,而GET通过URL查询参数传递数据。以下是两种常见的实现方式:

方式1:直接通过查询参数传递字段

如果要追加的行数据是零散字段(比如姓名、邮箱、手机号),可以直接把字段作为URL参数传递:

function doGet(e) {
  // 获取URL查询参数,示例请求URL:https://script.google.com/macros/s/xxx/exec?name=张三&email=zhangsan@example.com&phone=123456789
  const name = e.parameter.name;
  const email = e.parameter.email;
  const phone = e.parameter.phone;

  // 校验参数完整性
  if (!name || !email || !phone) {
    return ContentService.createTextOutput("参数不完整").setMimeType(ContentService.MimeType.TEXT);
  }

  // 打开目标表格(替换为你的表格ID和工作表名称)
  const sheet = SpreadsheetApp.openById("你的表格ID").getSheetByName("Sheet1");
  // 追加行到表格
  sheet.appendRow([name, email, phone]);

  // 返回成功响应
  return ContentService.createTextOutput("行已成功追加").setMimeType(ContentService.MimeType.TEXT);
}

方式2:通过查询参数传递JSON字符串

如果要传递整行的JSON数据(和原doPost逻辑更接近),可以把JSON字符串作为单个参数传递:

function doGet(e) {
  // 获取URL中的json参数,示例请求URL:https://script.google.com/macros/s/xxx/exec?json={"name":"张三","email":"zhangsan@example.com","phone":"123456789"}
  const jsonStr = e.parameter.json;
  if (!jsonStr) {
    return ContentService.createTextOutput("缺少json参数").setMimeType(ContentService.MimeType.TEXT);
  }

  try {
    // 解析JSON字符串为对象
    const body = JSON.parse(jsonStr);
    // 提取字段组装成行(根据你的表格列顺序调整)
    const row = [body.name, body.email, body.phone];

    // 打开目标表格并追加行
    const sheet = SpreadsheetApp.openById("你的表格ID").getSheetByName("Sheet1");
    sheet.appendRow(row);

    return ContentService.createTextOutput("行已成功追加").setMimeType(ContentService.MimeType.TEXT);
  } catch (error) {
    return ContentService.createTextOutput(`JSON解析错误:${error.message}`).setMimeType(ContentService.MimeType.TEXT);
  }
}

注意事项

  • 部署Web App时,需将权限设置为“任何人,甚至匿名用户”(若需公开访问),执行方式选择“我”。
  • GET请求存在URL长度限制,若传递大量数据,建议优先使用POST方式。
  • 测试时可直接在浏览器地址栏输入带参数的URL,或用curl、Postman发起GET请求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 13:45:26