繁体   English   中英

防止使用jQuery双重提交表单

[英]Prevent double submission of form using jQuery

问题:

我有一个脚本,用户可以在其中按C或M键选择一个选项。 一旦按下任一键,将提交表单。 由于有严格的规则,每个选项只能提交一次,因此有些按多次。

题:

我如何防止用户按下C或M键后再次提交表单? 我希望他们能够在提交后刷新页面后按任一键。

PHP / jQuery中的代码:

if (in_array($checkstring, $footer))
    {
        echo '
            <script type="text/javascript">
                $(document).ready(function()
                {
                    $(window).keypress(function(e)
                    {
                        if (e.which == 99)
                        {
                            $("input#left").val( 1 );
                            $("form").submit();
                        }
                        else if (e.which == 109)
                        {
                            $("input#right").val( 1 );
                            $("form").submit();
                        }
                    });

                    '.$warning.'
                });
            </script>
        ';
    }

我在想您正在寻找类似的东西:

这将创建一个布尔变量设置为false,并且如果变量为false并且key = C | M设置为true,则该函数将不会再次运行Submit,因为一旦为true而不是false

var once = false;
$(window).keypress(function(e){
    if(!once){
        if(e.which == 99){
            $("input#left").val( 1 );
            $("form").submit();
            once = true;
            //maybe a function to time out to reset once after x seconds?
        }else if (e.which == 109){
            $("input#right").val( 1 );
            $("form").submit();
            once = true;
            //maybe a function to time out to reset once after x seconds?
        }
    }
});
var once = false;
$(window).keypress(function(e){
    if(!once){
        if(e.which == 99 || e.which == 109){
            $("input#"+(e.which == 99)?"left":"right").val( 1 );
            $("form").submit();
            once = true;
        }
    }
});
     $(window).keypress(function(e)
    e.stopPropagation();
 /* here we apply this because when we press

 click then it takes form submit action

 so we prevent all the things when we

 press key as you mention in your code*/
                        {
                            if (e.which == 99)
                            {
                                $("input#left").val( 1 );
                                $("form").submit();
                            }
                            else if (e.which == 109)
                            {
                                $("input#right").val( 1 );
                                $("form").submit();
                            }
                        });

reference [event.stopPropagation()][1]


  [1]: http://api.jquery.com/event.stopPropagation/

暂无
暂无

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

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