【发布时间】:2019-04-08 22:44:41
【问题描述】:
我正在尝试创建依赖于电子表格内容的 html 模板。但是自从一周以来,我一直坚持将 GS 函数返回的值发送到 html 模板。当我调用位于 html 中的函数时,我得到了我期望的结果。但是当我调用位于 gs.code 文件中的相同函数时,我得到了未定义。我做错了什么?
这行得通,但没用:
HTML 文件:
<script>
function addOption() {
var x = document.getElementById("xBad");
var option = document.createElement("option");
option.text = newOpt();
x.add(option);
};
function newOpt() {
var str = "extra option";
return str;
}
</script>
但是当我替换返回额外选项到 gs 文件的函数时,在我需要它的地方,它添加了 undefined。
HTML 文件:
<script>
function addOption() {
var x = document.getElementById("xBad");
var option = document.createElement("option");
option.text = google.script.run.newOpt();
x.add(option);
}
</script>
GS 文件:
function newOpt() {
var str = "extra option";
return str;
}
我想,我已经阅读了所有关于这个的谷歌 API 文档以及在 stackoverflow 中与我相关的所有问题,但恐怕我找不到解释。唯一的一个答案,我理解建议 google.script.run 不返回值,直到没有 SuccessHandler 放入代码中,但我真的不知道,在这种情况下,什么条件可以成功或失败。
【问题讨论】:
-
要从 Javascript 调用 Google 脚本函数,请使用 google.script.run
-
看看这个example
-
google.script.run.newOpt() 异步运行,因此您需要 withSuccessHandler 否则 x.add 将在 newOpt() 完成之前执行。并且您编码的方式不会返回任何内容。参见 withSuccessHandler
标签: javascript html google-apps-script web-applications