解析表单提交与谷歌应用程序脚本

Parse Form Submission with Google Apps Script

本文关键字:应用程序 脚本 谷歌 表单提交      更新时间:2023-09-26

我有一个Google电子表格,它加载了一个带有HTML表单的边栏。该表单的代码如下:

<script>
function handleFormSubmit(formObject) {
    google.script.run.processForm(formObject);
}
</script>
<form id="myForm" onsubmit="handleFormSubmit(this)">
  PO#: <input type="text" name="po" required><br/>
  Invoice#: <input type="text" name="invoice" required><br/>
  <input type="submit" value="Submit" />
</form>
<div id="output"></div>

它与以下脚本一起工作:

function processForm(form) {  
  var ss = SpreadsheetApp.getActive();
  var sheet = ss.getSheetByName('Sheet5');
  var lr = sheet.getLastRow();
  var range = sheet.getRange(lr+1,1,1,1);
  range.setValue(form);
  Logger.log(form);
}

目前我得到{invoice=####, po=####}作为结果。如何解析(如果这是正确的术语)表单提交,以便每个响应可以转到不同的单元格?有没有办法把它变成一个数组?

谢谢

不完全确定你想在这里做什么,但我不认为你可以转移一个dom对象到谷歌应用程序脚本。你可以这样写:

<script>
function handleFormSubmit(formObject) {
    google.script.run.processForm({
        po: formObject.getElementById("po").value,
        invoice: formObject.getElementById("invoice").value
    });
}
</script>
<form id="myForm" onsubmit="handleFormSubmit(this)">
  PO#: <input type="text" name="po" id="po" required><br/>
  Invoice#: <input type="text" name="invoice" id="invoice" required><br/>
  <input type="submit" value="Submit" />
</form>
<div id="output"></div>

然后在你的Google Apps脚本中,使用

来获取输入的值
form.po

form.invoice

使用google.script.run.processForm()将表单传递回服务器。而不是使用获取最后一行,并添加+1,只是简单地使用appendRow()函数。

    function processForm(form) {  
       var ss = SpreadsheetApp.getActive();
       var sheet = ss.getSheetByName('Sheet5');
       sheet.appendRow(form) //accepts an array [val1,val2,val3]
    }