使用 keyup 上的 Submit() 提交表单两次

2024-05-15

我有一个与此类似的 jQuery/HTML 代码:

<form action="/SomeAction" method="post">
  <input id="my-textbox" type="text" placeholder="Write something and press enter to continue..." />
</form>

<script type="text/javascript">
 $(function() {
     $('#my-textbox').keyup(function(e) {
        var $textbox = $(this);
        if ($textbox.val().length > 0 && e.keyCode == 13) {
           $textbox.parent('form').submit();
        }
     });
 });
</script>

The purpose was to automatically submit the form when the user pressed the Enter key. I regularly use Firefox so everything was OK for me until I tested in Google Chrome and Internet Explorer.

When I pressed the Enter key in the later browsers, sometimes I would get the form submitted twice. This was easy to notice because I would get duplicate entries in my DB and I'd see two POSTs using Fiddler.

经过一些测试,我发现我的问题是 jQuery 代码,因为如果没有它,文本框会在输入时自动提交,并且使用此代码会产生第二个POST在某些浏览器中。

我的问题是:

为什么浏览器不能巧妙地阻止第二种表单发布(就像 Firefox 在我的测试中所做的那样)?

我是否应该在所有平台的所有主要浏览器中看到这种行为?

有没有办法改进此代码,以便我使用 JavaScript 执行提交,但不会提交两次表单?


为什么浏览器不能巧妙地阻止第二种表单发布(就像 Firefox 在我的测试中所做的那样)?

That is the default behavior. What if you didn't have your script and the default behavior was such that the form wouldn't POST on enter.

我是否应该在所有平台的所有主要浏览器中看到这种行为?

Yes

有没有办法改进此代码,以便我使用 JavaScript 执行提交,但不会提交两次表单?

使用全局mutex变量并在表单 POST 后设置它 - 在后续 POST 中检查它以进行验证。或者,从keyup处理程序并停止事件传播。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 keyup 上的 Submit() 提交表单两次 的相关文章

随机推荐