简体   繁体   English

提交表单时如何防止在刷新时重新提交表单

[英]How to prevent form resubmit on refresh while form is submitting

I'm using nodeJs, handlebars, and JavaScript to submit a form with the post action but form submission is taking time due to a lot of data to store in DB son while the form is submitting if someone refreshes the page it creates duplicate data in DB.我正在使用 nodeJs、handlebars 和 JavaScript 来提交带有 post 操作的表单,但由于在提交表单时有大量数据存储在 DB 子中,表单提交需要时间,如果有人刷新页面,它会在其中创建重复数据D B。 can you tell how can I prevent this from happening?你能告诉我如何防止这种情况发生吗?

I create a button to submit the form and submit using Js like this.我创建了一个按钮来提交表单并像这样使用 Js 提交。

 function sumitform() { var myform = document.getElementById("myForm"); myform.submit(); }
 <form id="myForm" action="/path/toNodePostApi" method="post"> <input name="name" value="{{{data}}}"> <input id="btnsubmit" class="btn" type="button" value="submit" onclick="sumitform()"> </form>

You can disable the button after is pressed, but this is not going to hold the user form "refresh" the page and re-submit the values.您可以在按下后禁用按钮,但这不会让用户表单“刷新”页面并重新提交值。

In my case I do a "Working or Submitting" icon while doing it, but you will have to validate on the server side.就我而言,我在执行此操作时会显示“正在工作或正在提交”图标,但您必须在服务器端进行验证。 This will only let the user know, that the page is working on something a wait before hitting refresh.这只会让用户知道页面正在处理某些事情,然后再点击刷新。

You could ask the user to confirm they want to leave (or reload, in this case) the page:您可以要求用户确认他们想要离开(或在这种情况下重新加载)页面:

window.onbeforeunload = function() {
    return true;
};

In addition you could store the data in session.此外,您可以将数据存储在会话中。 Check to see if there is data in session on page load.检查页面加载时会话中是否有数据。 If it is there, the page was reloaded and you can make an api call to take appropriate action on the server to remove the previously sent data (or prevent it from being sent again from the client in the first place).如果存在,则页面已重新加载,您可以进行 api 调用以在服务器上采取适当的操作以删除先前发送的数据(或首先防止它再次从客户端发送)。

document.getElementById("myForm").addEventListener("click", function(event){
  event.preventDefault()
});

It prevent from reloading on button click Clicking on a "Submit" button, prevent it from submitting a form Clicking on a link, prevent the link from following the URL它防止重新加载按钮单击单击“提交”按钮,防止提交表单单击链接,防止链接跟随 URL

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

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