提交时不重定向表单操作

Form action not redirecting on submit

我有一个有趣的情况,因为我正在制作一个直接输出到 Google Sheet 的 HTML 表单(更多信息在这里:https://github.com/jamiewilson/form-to-google-sheets)。但是,我的表单操作不会重定向,因为单击提交按钮时页面只是保持不变。 Google Sheet 记录输入,但不在网页上显示。我想重定向到一个完全不同的页面。

我注意到这是一个常见问题,但所有其他答案要么是 a) 重定向但不提交用户的响应,要么 b) 提交响应但没有重定向。

提前致谢。

  const scriptURL = 'https://script.google.com/macros/s/AKfycbyoQPDaaR1YTUFjkU7weJ_Y9uCTE7hoOK_5yUQVjE8EjVuEIRBh/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))
  })
<!doctype html>
<html>
 <head></head>
<body>

<form name="submit-to-google-sheet" action="https://www.google.com">
  <input name="email" type="text" placeholder="insert text">
  <input id="submit" name="submit" type="submit" value="Submit">
</form>

 </body>
</html>

比如,这个修改怎么样?如果事件可以取消,则preventDefault()用于取消事件。根据你的情况,我想提出2种模式。

简单模式:

作为一个简单的修改,删除e.preventDefault()怎么样?

发件人:

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))
})

收件人:

form.addEventListener('submit', e => {
  fetch(scriptURL, { method: 'POST', body: new FormData(form)})
    .then(response => console.log('Success!', response))
    .catch(error => console.error('Error!', error.message));
})

其他图案:

和其他pattern一样,如果你只想在fetch() returns没有报错的时候跳转,下面的修改怎么样?在这种情况下,不使用 action="https://www.google.com" of <form name="submit-to-google-sheet" action="https://www.google.com">

示例脚本:

form.addEventListener('submit', e => {
  e.preventDefault();
  fetch(scriptURL, {method: 'POST', body: new FormData(form)})
    .then(response => {
      console.log('Success!', response);
      window.location.href = "https://www.google.com";
    })
    .catch(error => console.error('Error!', error.message));
});

参考:

如果这些不是您想要的结果,我深表歉意。