简体   繁体   English

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

[英]Call a custom GAS function from external URL

I want to call a custom function I wrote within my Google Apps Script.我想调用我在 Google Apps 脚本中编写的自定义函数。 When I execute a getJSON I suppose it'll automatically run my doGet(e).当我执行 getJSON 时,我想它会自动运行我的 doGet(e)。

My Javascript:我的Javascript:

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

Is there a possible way to call one of my custom functions for example例如,有没有可能的方法来调用我的自定义函数之一

My Google Apps Script:我的 Google Apps 脚本:

function getNumberOfFans(e){ 
   //code here
}

Do I have to add some kind of extra function parameter to my URL?我是否必须在我的 URL 中添加某种额外的函数参数?

  • In either a "stand alone" or bound Apps Script file add a doGet(e) function.在“独立”或绑定的 Apps 脚本文件中添加doGet(e)函数。
  • Publish the Apps Script file as a Web App.将 Apps 脚本文件发布为 Web 应用程序。
  • Get the published URL of the Web App.获取 Web App 的发布 URL。
  • Add a search string parameter to the end of the URL.将搜索字符串参数添加到 URL 的末尾。

You can add search string parameters to the URL of the published Wep App.您可以将搜索字符串参数添加到已发布的 Wep 应用程序的 URL。

Here is an example:下面是一个例子:

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

The search string is at the end of the URL, after exec .搜索字符串位于 URL 的末尾,在exec之后。 You must add a question mark after exec and then name=value你必须在exec之后加上一个问号然后name=value

url/exec?name=value

Where name and value will be replaced with your choices.其中namevalue将替换为您的选择。

Put the event argument (denoted by the letter "e") into the doGet(e) function, not the function you want used.将事件参数(由字母“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;
};

The above code is for a GET request.上面的代码用于 GET 请求。 If you want to use a POST request, don't use a search string in the URL.如果要使用 POST 请求,请不要在 URL 中使用搜索字符串。 For a POST request, you will send information in the payload.对于 POST 请求,您将在有效负载中发送信息。 You'll still use e.parameter to access the data sent, but whatever is in e.parameter will be an object with key/value pairs.您仍将使用e.parameter来访问发送的数据,但e.parameter任何内容e.parameter将是具有键/值对的对象。 You'll need to know what the key (property) name is that was sent in the object.您需要知道在对象中发送的密钥(属性)名称是什么。

For an explanation on URL Parameters, see this documentation:有关 URL 参数的说明,请参阅此文档:

URL Parameters 网址参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM