简体   繁体   English

提交后重定向表单(表单操作)

[英]Redirect form after submission (Form Action)

I created a form using google apps script editor and I'm trying to open a link to a specific URL once the form is submitted我使用谷歌应用程序脚本编辑器创建了一个表单,并且在提交表单后尝试打开指向特定 URL 的链接

.html .html

<form name="submit-to-google-sheet" id="form" action="http://example.com" target="_top" 
onsubmit="myFunction()">

<input type="submit" value="Submit">
</form>

<script>
function myFunction() {
alert("The form was submitted. Please press okay to reload the page");
}
</script>

In this part在这部分

action="http://example.com"

I'm supposed to replace the example.com with the page URL where the form is (just to reload the whole page as the alert says) but the form action is not working for some reason.我应该用表单所在的页面 URL 替换 example.com(只是像警报所说的那样重新加载整个页面)但表单操作由于某种原因不起作用。 Any help ..任何帮助..

Below are the complete codes as in my dashboard:以下是我的仪表板中的完整代码:

Form.html表单.html

<!DOCTYPE html>
<html>
<body>
<style>
</style>

<div class="ss-form-container">
<div class="ss-top-of-page">
<div class="ss-form-heading">
<h1 class="ss-form-title" dir="ltr">Test</h1>
<div class="ss-form-desc ss-no-ignore-whitespace" dir="ltr">WELD DATE 
00</div>
<div class="ss-required-asterisk" aria-hidden="true" id="Required">* 
Required</div></div></div><br>

<form name="submit-to-google-sheet" id="form" action="http://example.com" 
target="_top" onsubmit="myFunction()">

<input name="TEXT" type="text" placeholder="text" required>

<input name="email" type="email" placeholder="Email" required>

<div class="ss-q-title">JOINT
<span class="ss-required-asterisk" aria-hidden="true">*</span></div>

<? var innerHTML= createInnerHTML(); ?>  
<select name="JOINT" id="JOINT" aria-label="JOINT" aria-required="true" 
required="">
<option value=""></option>
<? innerHTML.forEach(function(option) { ?>
<option value="<?= option.value ?>"><?= option.text ?></option>
<? }); ?>
</select>

<input type="submit" value="Submit" name="submit" id="Submit">
</form>

<script>
function myFunction() {
alert("The form was submitted. Please press okay to reload the page");
}
</script>

<script>
const scriptURL = 'https://script.google.com/macros/s/AKfycbwTGqZqLTAsOpSweMn0xgHP0sOJPsFg5ZShC1HqzVoDoNi5h5Y/exec'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then(response => console.log('Success!', response))
  .catch(error => console.error('Error!', error.message))
})
</script>

</div>
</body>
</html>

Code.gs代码.gs

function doGet() {
return HtmlService.createTemplateFromFile('Form.html')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}

var sheetName = 'Sheet1'
var scriptProp = PropertiesService.getScriptProperties()


function doPost (e) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)

 try {
 var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
 var sheet = doc.getSheetByName(sheetName)

 var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues() 
 [0]
 var nextRow = sheet.getLastRow() + 1

 var newRow = headers.map(function(header) {
  return header === 'timestamp' ? 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()
}
}


function createInnerHTML() {
var ss = SpreadsheetApp.getActive();
var names = ss.getSheetByName("CHOICES");
var namesValues = names.getRange(2,2,names.getLastRow()-1).getValues(); 
var innerHTML = [];
for (var i=0;i<namesValues.length;i++){
innerHTML.push({value:''+ namesValues[i][0], text:namesValues[i][0]});
};
return innerHTML;
}

Assuming that you want the following actions to happen when the form is submitted:假设您希望在提交表单时发生以下操作:

  • A new row is appended in Sheet1 of your spreadsheet.在电子表格的Sheet1中追加了一个新行。
  • You get redirected to the form.你被重定向到表单。

You can accomplish this by following these steps:您可以按照以下步骤完成此操作:

(1) Remove the following script from your html : (1) 从您的html删除以下脚本:

<script>
const scriptURL = 'https://script.google.com/macros/s/AKfycbwTGqZqLTAsOpSweMn0xgHP0sOJPsFg5ZShC1HqzVoDoNi5h5Y/exec'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
  .then(response => console.log('Success!', response))
  .catch(error => console.error('Error!', error.message))
})
</script>

(2) Change this line in your html : (2) 在你的html更改这一行:

<form name="submit-to-google-sheet" id="form" action="http://example.com" target="_top" 
onsubmit="myFunction()">

To this one:对此:

<form name="submit-to-google-sheet" id="form" method="POST" action="https://script.google.com/macros/s/AKfycbwTGqZqLTAsOpSweMn0xgHP0sOJPsFg5ZShC1HqzVoDoNi5h5Y/exec" target="_top" onsubmit="myFunction()">

(3) Change this in your Code.gs : (3) 在你的Code.gs改变这个:

 return ContentService
  .createTextOutput(JSON.stringify({ 'result': 'success', 'row': nextRow 
 }))
  .setMimeType(ContentService.MimeType.JSON)

To this:对此:

return doGet();

So the try block in doPost would be like this:所以doPosttry块将是这样的:

try {
  var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'));
  var sheet = doc.getSheetByName(sheetName);

  var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
  var nextRow = sheet.getLastRow() + 1;

  var newRow = headers.map(function(header) {
    return header === 'timestamp' ? new Date() : e.parameter[header]
  })

  sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])

  return doGet();
}

In this case, doPost returns doGet , so Form.html gets loaded after the previous form data is submitted to the spreadsheet.在这种情况下, doPost返回doGet ,因此Form.html在之前的表单数据提交到电子表格后被加载。

Update更新

In case you want to redirect to another URL, you can do the following.如果您想重定向到另一个 URL,您可以执行以下操作。

  • Add an onsubmit trigger that runs a function handleFormSubmit that receives the form as a parameter ( this ).添加一个onsubmit触发器,该触发器运行一个函数handleFormSubmit ,该函数接收表单作为参数 ( this )。 To do that, change this:为此,请更改以下内容:
<form name="submit-to-google-sheet" id="form" action="http://example.com" target="_top" onsubmit="myFunction()">

To this:对此:

  <form name="submit-to-google-sheet" id="form" action="http://example.com" 
  target="_top" onsubmit="handleFormSubmit(this)">
  • Next, the function handleFormSubmit calls a server-side function called addData , and passes the form to it as a parameter.接着,函数handleFormSubmit调用称为服务器侧功能addData ,并将形式它作为参数。 So add this script in your HTML:所以在你的 HTML 中添加这个脚本:
<script>
  function handleFormSubmit(formObject) {
    google.script.run.addData(formObject);
  }
</script>

Finally, addData (previously doPost ) receives the form object as parameter:最后, addData (以前是doPost )接收表单对象作为参数:

function addData(data) {
var lock = LockService.getScriptLock()
lock.tryLock(10000)

 try {
   var doc = SpreadsheetApp.openById(scriptProp.getProperty('key'))
   var sheet = doc.getSheetByName(sheetName)

   var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0]
   var nextRow = sheet.getLastRow() + 1

   var newRow = headers.map(function(header) {
     return header === 'timestamp' ? new Date() : data[header]
   })

   sheet.getRange(nextRow, 1, 1, newRow.length).setValues([newRow])
 }

 catch (e) {
 return ContentService
  .createTextOutput(JSON.stringify({ 'result': 'error', 'error': e }))
  .setMimeType(ContentService.MimeType.JSON)
  }

finally {
lock.releaseLock()
}
}

I hope this is of any help.我希望这有任何帮助。

You can use prevent default on the form and open a new window using JS method您可以在表单上使用 prevent default 并使用 JS 方法打开一个新窗口

window.open()窗口.open()

This will not work on StackOverflow because of safety reasons.由于安全原因,这不适用于 StackOverflow。

 document.getElementById('Form').addEventListener('submit', function(evt){ evt.preventDefault(); window.open("http://www.example.com", "_top") })
 <form id = "Form"> <input type="submit" value="Submit"> </form>

Your code is working fine.您的代码运行良好。 form is being submitted to provided action.正在提交表单以提供操作。

<form name="submit-to-google-sheet" id="form" action="http://example.com" target="_top" onsubmit="myFunction()">
    <input type="submit" value="Submit">
</form>

and js part:和js部分:

function myFunction() {
    alert("The form was submitted. Please press okay to reload the page");
}

Check fiddle: http://jsfiddle.net/cm59koat/1/检查小提琴: http : //jsfiddle.net/cm59koat/1/

Okay everyone, I tried the below code and worked for me, Keep everything in the question as it is but change this part only:好的,大家,我尝试了以下代码并为我工作,保留问题中的所有内容,但仅更改此部分:

<script> const scriptURL = 'Script URL'
const form = document.forms['submit-to-google-sheet']
form.addEventListener('submit', e => { e.preventDefault()
window.open(After submit URL)
fetch(scriptURL, { method: 'POST', body: new FormData(form)})
.then(response => console.log('Success!', response))
.catch(error => console.error('Error!', error.message)) })
</script>

This will keep the form posting to the linked sheet as well as redirect your form to the added URL after submit这将使表单保持发布到链接的工作表,并在提交后将您的表单重定向到添加的 URL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM