google 应用程序脚本:html - 表单提交,获取输入值

google apps script: html - form submit, get input values

我正在尝试使用带有表单的边栏来获取用户输入。代码绑定到 Google 表格文件。

Code.gs:

function onOpen() {
  SpreadsheetApp.getUi()
      .createMenu('Custom Menu')
      .addItem('Show sidebar', 'showSidebar')
      .addToUi();
}

function showSidebar() {
  var html = HtmlService.createHtmlOutputFromFile('Page')
      .setTitle('My custom sidebar')
      .setWidth(300);
  SpreadsheetApp.getUi()
      .showSidebar(html);
}

function processForm(formObject) {
  var ui = SpreadsheetApp.getUi();
  ui.alert("This should show the values submitted.");
}

Page.html:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    Please fill in the form below.<br><br>
    <form id="myForm" onsubmit="google.script.run.processForm(this)">
      First name:
      <input type="text" name="firstname"><br><br>
      Last name:
      <input type="text" name="lastname"><br><br>
      Gender:<br>
      <input type="radio" name="gender" value="male" checked> Male<br>
      <input type="radio" name="gender" value="female"> Female<br>
      <input type="radio" name="gender" value="other"> Other<br>
      <br>
      <input type="submit" value="Submit">
    </form><br>
    <input type="button" value="Cancel" onclick="google.script.host.close()" />
  </body>
</html>

当我按 "Submit" 时,警报打开并显示给定的消息,我的浏览器打开 url,其中显示空白页面 (https://n-ms22tssp5ubsirhhfqrplmp6jt3yg2zmob5vdaq-0lu-script.googleusercontent.com/userCodeAppPanel?firstname=&lastname=&gender=male)。 我希望警报显示提交的值,但我不想打开额外的页面。

很简单的问题,但我读到的一切似乎都太复杂了。我只想知道获取用户输入的最简单方法。

Html 表单具有导航到提交 link 的默认行为。为了防止这种默认行为,您可以在 HTML 中使用 event.preventDefault() 函数,如下所示:

 <form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this)">

注意:你可以找到更详细的解释here

表单元素作为对象发送到 processForm 函数的参数中,要查看它们,您可以使用 JSON.stringfy(). Learn more about objects here

您的 processForm 函数将被修改为:

function processForm(formObject) {
  var ui = SpreadsheetApp.getUi();
  ui.alert(JSON.stringify(formObject))
  // To access individual values, you would do the following
  var firstName = formObject.firstname 
  //based on name ="firstname" in <input type="text" name="firstname">
  // Similarly
  var lastName = formObject.lastname
  var gender = formObject.gender
  ui.alert (firstName+";"+lastName+";"+gender)
}

我觉得对于html表单,默认的提交方式是GET,提交的表单数据会在页面地址栏可见。

您可以尝试将方法更改为POST:

  <form id="myForm" onsubmit="event.preventDefault(); google.script.run.processForm(this) method="post"">

参考这个linkhttps://www.w3schools.com/html/html_forms.asp#method

编辑:我试过了,发现我们仍然需要添加 event.preventDefault();