从外部调用自定义 GAS 函数 URL

Call a custom GAS function from external URL

我想调用我在 Google Apps 脚本中编写的自定义函数。当我执行 getJSON 时,我想它会自动 运行 我的 doGet(e)。

我的Javascript:

$.getJSON(https://script.google.com/macros/s/[ID]/exec, function(data){ 
   //code here
});

是否有可能调用我的自定义函数之一,例如

我的 Google Apps 脚本:

function getNumberOfFans(e){ 
   //code here
}

我是否必须向 URL 添加某种额外的函数参数?

  • 在 "stand alone" 或绑定的 Apps 脚本文件中添加一个 doGet(e) 函数。
  • 将 Apps 脚本文件发布为 Web 应用程序。
  • 获取已发布的 URL Web 应用程序。
  • 将搜索字符串参数添加到 URL 的末尾。

您可以将搜索字符串参数添加到已发布的 Wep 应用程序的 URL。

这是一个例子:

https://script.google.com/macros/s/[ID]/exec?searchStringName=functionOne

搜索字符串在 URL 的末尾,在 exec 之后。 exec后必须加问号,然后是name=value

url/exec?name=value

其中 namevalue 将替换为您的选择。

将事件参数(用字母 "e" 表示)放入 doGet(e) 函数,而不是您要使用的函数。

function doGet(e) {
  var passedString,whatToReturn;

  passedString = e.parameter.searchStringName;
  if (passedString === 'functionOne') {
    whatToReturn = functionOne();  //Run function One
  };

  return ContentService.createTextOutput(whatToReturn);
};

function functionOne() {
  var something;

  //. . . . Code;
  something = code here;
  return something;
};

以上代码用于 GET 请求。如果您想使用 POST 请求,请不要在 URL 中使用搜索字符串。对于 POST 请求,您将在负载中发送信息。您仍将使用 e.parameter 来访问发送的数据,但是 e.parameter 中的任何内容都将是具有 key/value 对的对象。您需要知道在对象中发送的密钥 (属性) 名称是什么。

有关 URL 参数的说明,请参阅此文档:

URL Parameters