【问题标题】:how to use google.script.run as if it was a function如何像使用函数一样使用 google.script.run
【发布时间】:2012-07-14 20:08:55
【问题描述】:

在 Google Apps 脚本中,我有以下脚本:

function doGet() {
  return HtmlService.createHtmlOutputFromFile('mypage');
}

function writeSomething() {
  return "<h1>hi people</h1>";
}

以及以下html文件:

<html>
  <a id="caller" href="#">update</a>
  <br>
  <div id="div">waiting...</div>
<script>
function go() {
  var a=google.script.run.writeSomething();
  document.getElementById("div").innerHTML=a;
}
document.getElementById('caller').onclick = go;
</script>
</html>

当我点击“更新”链接时,div 内容从“等待...”变为“未定义”。我想 google.script.run 不能作为函数调用。 那么,我该如何解决这个麻烦呢? (显然,这是一个玩具示例;我需要一种从脚本而不是 html 文件更新 div 内容的方法)

【问题讨论】:

    标签: google-apps-script


    【解决方案1】:

    函数 writeSomething() 是异步运行的,所以它会发生,但不会像本地函数那样返回响应。 (这是 JavaScript 与服务器对话的标准)。相反,您需要指定一个“回调”函数,该函数在 writeSomething() 完成时被调用。

    这是您的 HTML 的更正版本:

    <html>
      <a id="caller" href="#">update</a>
      <br>
      <div id="div">waiting...</div>
    <script>
    function callback(whatToWrite) {
      document.getElementById("div").innerHTML=whatToWrite;
    }
    function go() {
      google.script.run.withSuccessHandler(callback).writeSomething();
    }
    document.getElementById('caller').onclick = go;
    </script>
    </html>
    

    或者等价的,你可以内联指定回调函数:

    ...
    <script>    
    function go() {
      google.script.run.withSuccessHandler(function(whatToWrite) {
        document.getElementById("div").innerHTML=whatToWrite;
      }).writeSomething();
    }
    ...
    

    【讨论】:

    • 那么如果“

      hi people

      ”实际上是一个交互式jquery元素(您可以选择)并且您希望将选择的索引返回到谷歌应用脚​​本?关于如何做到这一点的任何想法?或者换句话说:如何将“

      hi people

      ”返回到 google apps 脚本,以便您可以在该环境中进一步编辑它?
    • 出于某种原因,我无法理解本示例中使用的函数名称,whatToWrite、WriteSomething、...函数参数呢?在回调中应该如何处理?
    • 天啊,@CoeryG!你是第一个在我的大脑中理解这一点的人,现在我有一个工作基础来构建更多动态工具。谢谢!谢谢!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 1970-01-01
    • 2013-08-19
    • 1970-01-01
    • 2022-10-12
    • 2020-01-05
    相关资源
    最近更新 更多