onunload - 检查表单是否已提交
我的网页上有一个表单。当用户离开该页面时,我想检查表单是否已提交。如果是,则用户只需继续进入下一页,如果不是,则用户会收到一条警报消息,并返回到表单所在的原始页面。
我对 javascript 不太熟悉,所以如果可能的话,我希望能提供一些代码片段?
GF
I have a form on a webpage.when the user moves from that page, I want to check that the form was submitted. If it was, then the user simply continues to the next page, if not, the user receives an alert msg and is brought back to the original page where the form resides.
I am not too familiar with javascript so I would appreciate some code snippets if that's possible?
GF
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的问题有点模糊。您的问题意味着您正在异步提交表单,但您说您不熟悉 JavaScript。异步提交表单需要 JS 知识。另外,如果您实际上同步提交表单,那么解决方案就太明显了(只需在服务器端有条件地渲染一些 JS 即可)。
如果您实际上是异步提交表单,那么只需在成功提交表单后在表单的
data-xxx
属性中设置一些令牌/切换即可。例如,然后,在
beforeunload
事件期间,您只需检查令牌/切换是否存在,如果丢失,则相应地返回消息。请注意,您不能为此使用
unload
事件,因为为时已晚,无法保持页面打开。更新:因此表单同步提交。好吧,无论你使用什么服务器端语言,只要让它在表单未提交时有条件地渲染一个 JS
window.onbeforeunload
调用即可(你显然已经知道表单何时提交,否则怎么办?你能处理吗?;))。您还需要在即将提交表单时禁用window.onbeforeunload
调用。根据您的问题历史记录,我打赌您了解 PHP,因此这里有一个针对 PHP 的启动示例:
Your question is a bit vague. Your question implies that you're submitting the form asynchronously, but you said that you aren't familiar with JavaScript. Submitting a form asynchronously requires JS knowledge. Also, if you're actually submitting the form synchronously, the solution would have been too obvious (just render some JS conditionally on the server side).
If you're actually submitting the form asynchronously, then just set some token/toggle in as form's
data-xxx
attribute after the succesful form submit. E.g.Then, during
beforeunload
event you just check if the token/toggle is there and in case it's missing, return the message accordingly.Note that you can't use
unload
event for this since it too late then to keep the page open.Update: so the form is submitted synchronously. Okay, whatever server side language you're using, just let it conditionally render a JS
window.onbeforeunload
call when the form is not submitted (you obviously already know when the form is been submitted, how else would you be able to process it? ;) ). You also need to disable thewindow.onbeforeunload
call when the form is about to be submitted.Based on your question history I bet that you know PHP, so here's a PHP targeted kickoff example: