如何防止ajax驱动的表单被提交两次?
我在开发 Grails 应用程序时迈出了使用 Ajax 的第一步。我正在
<g:form ...>
<g:submitToRemote ... />
</g:form>
以最简单的方式使用它,开箱即用,效果很好(感谢 grails!)。问题是,Ajax 调用需要大约 2 秒才能返回并更新 html(至少在测试系统上),在此期间,用户可以(实际上经常)再次点击提交按钮。目前,这会导致进行第二次调用,最终破坏输出(错误消息表示,不能两次提交相同的数据)。
防止这种情况的最佳方法是什么?
预先感谢您的意见!
I am taking my first steps with Ajax while working on a Grails application. I am using
<g:form ...>
<g:submitToRemote ... />
</g:form>
in the most simple way and it worked great out of the box (Thanks grails!). The problem is, that the Ajax call needs about 2 seconds to return and update the html (at least on the test system) and during that time, the user can (and actually does quite often) hit the submit button again. At the moment this results in a 2nd call being made that finally ruins the output (an error msg says, that one cannot submit the same data twice).
What is the best way to prevent this?
Thanks in advance for your input!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
处理此问题的最佳方法是 禁用提交onSubmit() 函数中的按钮。老实说,我不知道为什么更多的网站不这样做。我经常进行下一步,而不是禁用提交按钮,而是将提交按钮放在 span 标记中,并将 span 标记的内容替换为静态文本“请稍候...”,这样您的用户就可以获得他们按下的视觉反馈按钮和“高层正在努力”。
The best way to handle this is to disable the submit button in your onSubmit() function. Honestly, I don't know why more sites don't do this. I often go the next step and instead of disabling the submit button, I put the submit button in a span tag and replace the contents of the span tag with static text "Please wait..." That way your users get visual feedback they pressed the button and "top men are working on it".
正如 dj_segfault 所说,你可以做到这一点。
如果您想在控制器中验证这一点,请查看官方文档中的“处理重复的表单提交”:
http://grails.org/doc/latest/guide/theWebLayer.html#formtokens
As dj_segfault said you can do that.
If you want to validate this in your controller, take a look in "Handling Duplicate Form Submissions" in the official docs:
http://grails.org/doc/latest/guide/theWebLayer.html#formtokens