首页 > 解决方案 > 从谷歌脚本到 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 上)。

谢谢

标签: javascriptgoogle-apps-script

解决方案


您没有实现作为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


推荐阅读