在Apps脚本功能中获取html文本框的值

use*_*075 6 html javascript textbox google-apps-script

这里出了点问题,我从其他有类似问题的人那里得到的所有建议似乎都没有用.

我有两个文件:google脚本中的myPage.html和myCode.gs.我已经将html文件部署为Web应用程序,并且我已经找到了(如果有帮助)如何使用'submit'按钮的onclick事件来触发myCode.gs文件中的emailTech函数就好了.

现在我想将html文件中的文本框中的值插入从onClick事件调用的电子邮件中.我试过document.getElementById('textBoxId').value,但是我得到以下错误"参考错误:"文档"未定义."是什么给出的?

myPage.html文件:

<html>
<head>
    <title>Test Page</title>
</head>
<body>
<input type="button" onClick="google.script.run.emailTech();" value="Submit" />

<input type="text" value=" " id = "textBox" name = "textBox" />
</body>
    <script type="text/javascript">
    </script>
</html>
Run Code Online (Sandbox Code Playgroud)

myCode.gs文件:

  function doGet() {
  return HtmlService.createHtmlOutputFromFile('myPage');
}

function emailTech(){

  var nameBox = document.getElementById('textBox').value;
  var message = "This is the text box value" + nameBox;
  MailApp.sendEmail("123@xyz.com", "This is the subject", message );
}
Run Code Online (Sandbox Code Playgroud)

Mog*_*dad 8

错误消息是正确的 - 在您的Apps脚本功能中emailTech(),在命名的范围内没有变量document.

您有两种不同的方式来部署Apps Script WebApps.由于您使用的是HTML服务(并且您的用户界面是一个html文件),因此您无法使用UI服务方法(如getElementById())来访问输入值.所以,你会做一些不同的事情.

要将提交按钮和输入字段绑定在一起,请使用包含在<form>标记中的表单.提交按钮仍然具有onclick功能,但现在它将是嵌入在HTML中的javascript函数,它将把表单中的所有输入传递给您的emailTech()函数.

在您的应用程序脚本端处理程序中,您将收到表单输入作为对象,表单中的字段作为键值对.关键是name来自现场.

本答案中描述了一般解决方案.这是适合您代码的版本.我遗漏了Arun所说的成功和失败处理.当然,在现实生活中部署之前,您应该构建错误检查.

Code.gs

function doGet() {
  return HtmlService.createHtmlOutputFromFile('myPage');
}

function emailTech(form){

  var nameBox = form.techEmail;
  var message = "This is the text box value" + nameBox;
  MailApp.sendEmail("email@somewhere.com", "This is the subject", message );

}
Run Code Online (Sandbox Code Playgroud)

myPage.html下

<html>

    <head>
        <title>Test Page</title>
    </head>

    <body>
        <form>
            <input type="text" value=" " name="techEmail" />
            <input type="button" onClick="formSubmit()" value="Submit" />
        </form>
    </body>
    <script type="text/javascript">
        function formSubmit() {
            google.script.run.emailTech(document.forms[0]);
        }
    </script>

</html>
Run Code Online (Sandbox Code Playgroud)