gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 05:25:54 26 4
gpt4 key购买 nike

在 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com