表单在keyup上使用submit()提交两次 [英] Form submitted twice using submit() on keyup

查看:217
本文介绍了表单在keyup上使用submit()提交两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I had a jQuery / HTML code similar to this:

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

目的是在用户按下Enter键时自动提交表格。我经常使用Firefox,所以一切都对我好,直到我在谷歌浏览器和Internet Explorer中测试。

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.

当我在后面的浏览器中按Enter键时,有时我会得到表格提交两次。这很容易被注意到,因为我会在我的数据库中获得重复的条目,并且我会看到两个 POST 使用Fiddler。

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 在某些浏览器中。

After some testing, I found out that my problem was the jQuery code, since the textbox would submit automatically on enter without it, and using this code would produce a second POST in some browsers.

我的问题是:

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

Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?

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

Should I expect this behavior in all major browsers in all platforms?

有没有办法改进这段代码,所以我使用JavaScript执行提交,但是没有提交两次表单?

Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?

推荐答案


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

Why don't browsers smartly prevent the second form post (like Firefox did in my testing)?

这是默认行为。如果你没有你的脚本并且默认行为是这样的,那么表格不会在上输入

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.


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

Should I expect this behavior in all major browsers in all platforms?


有没有办法改进这段代码,所以我使用JavaScript执行提交,但是没有提交两次表单?

Is there a way to improve this code so I perform the submit using JavaScript, but don't get the form submitted twice?

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

Use a global mutex variable and set it once the form POSTs - checking it on subsequent POSTs to validate. Or, return false from the keyup handler and stop the event propagation.

这篇关于表单在keyup上使用submit()提交两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆