我已将 Google Apps 脚本设置为 WebApp,以从 HTML 表单(非 Google 表单)获取表单数据并将结果插入 Google 表格。一切正常,但我试图获取自定义登录页面而不是当前的 Apps 脚本页面,这对最终用户来说没有用。
我用这个作为参考:https://github.com/levinunnink/html-form-to-google-sheet
本 GitHub 指南的末尾有一些信息,但它不是描述性的,我在此处或 GitHub 上找不到任何可用的内容。我了解一些 JS,但我不是专家,真的可以用手来解决这个问题。以下是我所拥有的,这是我所得到的最接近所有工作的内容。
这是我的 HTML。
<script>
function myFunction()
{ alert("The form was submitted successfully. Please press okay to continue...");
window.open("URL-to-thanks-page", "_top");
}
</script>
<form class="googleform" name="googleform" id="googleform" target="_top" method="POST" onsubmit="myFunction()" action="MY-GOOGLE-APPS-SCRIPTS-URL">
<!--FORM STUFF-->
<button type="submit" class="btn-default btn" name="submit" access="false" style="default" id="submit">Submit</button>
</form>
这是我的Code.gs
const sheetName = 'RSVP'
const scriptProp = PropertiesService.getScriptProperties()
function intialSetup () {
const activeSpreadsheet = SpreadsheetApp.getActiveSpreadsheet()
scriptProp.setProperty('key', activeSpreadsheet.getId())
}
function doPost (e) {
const lock = LockService.getScriptLock()
lock.tryLock(10000)
try {
const doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
const sheet = doc.getSheetByName(sheetName)
const headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
const nextRow = sheet.getLastRow() + 1
const newRow = headers.map(function(header) {
return header === 'Date' ? new Date() : e.parameter[header]
})
sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow }))
.setMimeType(ContentService.MimeType.JSON)
}
catch (e) {
return ContentService
.createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
.setMimeType(ContentService.MimeType.JSON)
}
finally {
lock.releaseLock()
}
}
任何帮助将不胜感激。
谨此,
我实际上已经弄清楚了。我使用了原始指南上的代码并进行了修改。在我的 HTML 中,我删除了之前的
<script>
部分并将其更改为以下内容:
<script>
window.addEventListener("load", function() {
const form = document.getElementById('googleform');
form.addEventListener("submit", function(e) {
e.preventDefault();
const data = new FormData(form);
const action = e.target.action;
fetch(action, {
method: 'POST',
body: data,
})
.then(() => {
window.location.href = 'URL of thank you page';
})
});
});
</script>
这解决了问题,现在一切正常。