javascript - 从谷歌脚本到 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] 中设置了它),它将testReturn
从 code.gs 接收函数中返回的值。
对于您的 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>
基本上,使用 [2] 从 html 调用 Apps 脚本函数 (code.gs)google.script.run
不会直接返回值,而是您必须使用在一个或多个处理函数中设置的回调函数来管理响应 [ 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
推荐阅读
- android - SSLCOMMERZ 正在调试 apk 但不在发布 apk
- elasticsearch - 与聚合一起使用时,search_after 是否仍然有益?
- react-native - React Native google-signin 在开发模式下工作正常,但在发布 apk 中,这不起作用
- c++ - 使用 *this 从右值进行的预期无效初始化
- docker - 关于 hyperledger-fabric 中的 orderer 容器
- html - CSS 不起作用和来自 HTML 的 DOM 结构
- c# - 将多个外键映射到一个实体
- python - 基于不同列中特定值的计算的新列
- android - 无法识别 Flutter 导入
- reactjs - 如何在 mern 堆栈中获取注册表单的国家/地区列表?