如何像使用函数一样使用 google.script.run [英] how to use google.script.run as if it was a function

查看:26
本文介绍了如何像使用函数一样使用 google.script.run的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a Google Apps Script, I have the following script:

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

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

以及以下 html 文件:

and the following html file:

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

When I click on the "update" link, the div content changes from "waiting..." to "undefined". I suppose that google.script.run cannot be called as a function. So, how can I solve this trouble? (obviously, this is a toy example; I need a way to update the div content from the script and not from the html file)

推荐答案

函数 writeSomething() 是异步运行的,因此它会发生,但不会像本地函数那样返回响应.(这是 JavaScript 与服务器通信的标准).相反,您需要指定一个在 writeSomething() 完成时调用的回调"函数.

The function writeSomething() is run asynchronously so it happens but doesn't return the response as a local function would. (This is standard for JavaScript talking to a server). Instead, you need to specify a "callback" function which gets invoked when writeSomething() is finished.

这是您的 HTML 的更正版本:

Here's the corrected version of your 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>

或者等效地,您可以指定内联回调函数:

Or equivalently, you can specify the callback function inline:

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

这篇关于如何像使用函数一样使用 google.script.run的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆