如何实现Google Sheets表单提交后重定向回原网站页面?
解决Google Sheets表单提交后无法重定向回原页面的问题
解决这个问题有两种常用方案,按需选择:
方案一:前端异步提交(推荐,无页面跳转体验更流畅)
传统form提交会直接跳转至脚本页面,改用JS拦截提交事件,异步发送数据,成功后自主控制跳转逻辑。
修改后的HTML代码:
<form id="form"> <label for="fname">First name:</label><br> <input type="text" id="fname" name="fname" placeholder="John"><br> <label for="lname">Last name:</label><br> <input type="text" id="lname" name="lname" placeholder="Doe"><br> <button type="submit">Send</button> </form> <script> document.getElementById('form').addEventListener('submit', async function(e) { e.preventDefault(); // 阻止表单默认跳转行为 const formData = new FormData(this); try { const response = await fetch('https://script.google.com/macros/s/AKfycbyJJc1i3740zFxXMgxBQPowxwND5Cxb-n4a2ZnYphvLfrBqNfnqlFOcmHpfwMNh_jk/exec', { method: 'POST', body: formData }); const result = await response.json(); // 提交成功后的逻辑:显示提示+跳转 alert('提交成功!我们会尽快联系你'); window.location.href = 'https://你的原页面URL'; // 替换为你的原网站页面地址 } catch (error) { alert('提交失败,请重试'); console.error(error); } }); </script>
注意:移除原form标签的action和method属性,替换window.location.href的值为你的原页面地址。
方案二:修改Google Apps Script返回重定向响应
如果不想改动前端代码,直接修改后端脚本,让它返回一个带自动跳转逻辑的HTML页面:
修改后的App Service代码:
const sheetName = 'Sheet1' const scriptProp = PropertiesService.getScriptProperties() function initialSetup () { 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]) // 替换为你的原页面URL,可调整跳转延迟时间 const redirectUrl = 'https://你的原页面URL'; return HtmlService.createHtmlOutput(` <!DOCTYPE html> <html> <body> <p>Thanks for submitting! Someone from our team will reach out to you!</p> <p>正在跳转回原页面...</p> <script> setTimeout(() => { window.location.href = "${redirectUrl}"; }, 2000); // 2秒后跳转,单位毫秒 </script> </body> </html> `); } catch (e) { // 提交失败时的跳转逻辑 const redirectUrl = 'https://你的原页面URL'; return HtmlService.createHtmlOutput(` <!DOCTYPE html> <html> <body> <p>提交失败:${e.message}</p> <p>正在跳转回原页面...</p> <script> setTimeout(() => { window.location.href = "${redirectUrl}"; }, 3000); </script> </body> </html> `); } finally { lock.releaseLock() } }
注意:替换两处redirectUrl的值为你的原页面地址,跳转延迟时间可根据需求调整。
内容的提问来源于stack exchange,提问作者Roshanay Asif Sheikh
相关产品推荐
相关产品推荐

