[英]from google script to html
我在 .gs 文件中有一个函数:
function testReturn(){
return "Finaly it works!";
}
另一个在 html 文件中:
<script>
window.addEventListener('load', function() {
google.script.run.withSuccessHandler(createPost).testReturn();
});
/**/
document.getElementById("go_button").addEventListener("click",functionGo);
function functionGo(){
var textToDisplay = google.script.run.testReturn();
document.getElementById("input1_id").value = textToDisplay;
}
</script>
回报总是“未定义的”。 如何在 gs 和 html 脚本之间进行交互? (当然,我不仅想返回一个整数,该项目是要获得一个用许多函数编写的长文本,我只是在寻找一种方法来获取结果并将其显示在 html 上)。
谢谢
您没有实现createPost
函数,它是回调函数(因为您在withSuccessHandler
函数 [1] 中设置了它),它将从 code.gs 接收testReturn
函数中返回的值。
对于您的 html,以下代码将在页面加载后立即更新输入值。 如果您有一个 id 设置为“input1_id”的输入元素,它应该对您有用:
<script>
window.addEventListener('load', function() {
google.script.run.withSuccessHandler(createPost).testReturn();
});
function createPost(returnedValue){
document.getElementById("input1_id").value = returnedValue;
}
</script>
如果您想要在单击按钮后更新输入值,则可以改用它(假设您有一个带有“go_button”作为 ID 的按钮):
<script>
document.getElementById("go_button").addEventListener("click",functionGo);
function functionGo(){
google.script.run.withSuccessHandler(createPost).testReturn();
}
function createPost(returnedValue){
document.getElementById("input1_id").value = returnedValue;
}
</script>
基本上,使用google.script.run
[2] 从 html 调用 Apps 脚本函数 (code.gs) 不会直接返回值,而是您必须使用一个或多个回调函数来管理响应处理程序函数 [1] (如本例中的withSuccessHandler
)。
[1] https://developers.google.com/apps-script/guides/html/communication#success_handlers
[2] https://developers.google.com/apps-script/guides/html/reference/run
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.