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