google-apps-script - 如何像使用函数一样使用 google.script.run

标签 google-apps-script

在 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 内容)

最佳答案

函数 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();
}
...

关于google-apps-script - 如何像使用函数一样使用 google.script.run,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11487045/

相关文章:

google-apps-script - 如何在谷歌电子表格应用程序中使用 Browser.msgBox 响应?

google-apps-script - 向 Html 模板添加属性会出现错误 "Object does not allow properties to be added or changed"

google-apps-script - Google App 脚本删除驱动器中的所有文件

google-apps-script - 以编程方式测试 Google Sheet 单元格是否在命名范围内

google-apps-script - 在谷歌脚本中使用自定义顺序对列进行排序

google-apps-script - 有没有办法撤销谷歌应用程序脚本所做的更改?

javascript - 删除 Google Script 中的文件 .setTrashed 'You do not have authorization to perform that action.'

google-apps-script - 关闭时运行 Google Sheets 脚本

javascript - Google Apps 脚本通过电子表格发送电子邮件不起作用

javascript - 使用 Google 脚本对 API 调用进行身份验证