首页 > 解决方案 > 使用回调从 HTML 发送输入

问题描述

我有用户输入的代码,我有回调,我只是对如何使用回调发送数据感到困惑

我的代码:

HTML

<!DOCTYPE html>

<html>

<head>

<base target="\_top">

</head>

<body>

<label>User info: </label>

<div align="justify">

<input type= "text" id = "email">

</div>

<br>

<button id="searchData"> Search data sheet </button>

<script> 
//Above creates a box for user input [//document.getElementById](//document.getElementById)("searchData").addEventListener("click",addHeaders); document.getElementById("searchData").addEventListener("click",google.script.run.withSuccessHandler(onSuccess).testCase()); 
//gets the button1 element and listens for a click then runs the function addName. 
function onSuccess(numUnread) { 
var div = document.getElementById('output'); 
div.innerHTML = numUnread 
} &#x200B; 
google.script.run.withSuccessHandler(onSuccess).testCase() 
</script>

</body>

</html>

应用脚本

function doGet() {

  return HtmlService.createHtmlOutputFromFile('frontEnd');

}

function testCase(input)

{

  Logger.log((input + ' hello'))

  return (input + ' hello')

}

我的预期是输入+“你好”,而不是“未定义的你好”

标签: google-apps-script

解决方案


假设在您的 html 中,您有一个像这样的按钮,上面有一个 div:

<body>
<div id="message"></div>
<input type="button" value="Hello" onClick="sayHello();" />

<script>
  //When you click the button this function gets called
  function sayHello() {
    google.script.run
    .withSuccessHandler(function(msg){
       document.getElementById("message").innerHTML=msg;//message will appear in the div
     })
    .sayHelloToServer();//This function is on the server
    console.log('My Code');
</script>
</body>

然后在 Code.gs 中:

function sayHelloToServer() {
  return "Hello.  We're very happy that you came to visit us.";//this is returned to withSuccessHandler(function(msg){}) or you can also use a standalone function in which you simply put its name in like this .withSuccessHandler(funcname)
}

这在客户端到服务器通信中进行了解释


推荐阅读