简体   繁体   English

Ajax表单提交两次

[英]Ajax form submitting twice

My Ajax form is submitting twice for some reason even using preventDefault() and return false . 由于某种原因,我的Ajax表单提交了两次,甚至使用了preventDefault()return false

<script type="text/javascript">
    $("#form_codes").submit(function(e) {
        e.preventDefault();
        $.ajax({
            data: $('#form_codes').serialize(),
            type: 'POST',
            url: '{{url('save_code')}}',
            success: function(msg) {
                         $('#product_codes > tbody:last-child').append('<tr><td>' + $('#code').val() + '</td><td>' + $('#description').val() + '</td></tr>');
                         $('#code').val('');
                         $('#description').val('');
                     },
            error: function(msg) {

                   }
        });         
        return false;
    });
</script>

Try adding e.stopImmediatePropagation() to the submit event, as it prevents every other event from executing so this may stop the second form submit. 尝试将e.stopImmediatePropagation()添加到e.stopImmediatePropagation()事件中,因为它阻止其他所有事件的执行,因此这可能会停止第二个表单的提交。

<script type="text/javascript">
                $("#form_codes").submit(function(e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                    $.ajax({
                        data: $('#form_codes').serialize(),
                        type: 'POST',
                        url: '{{url('save_code')}}',
                        success: function(msg) {
                            $('#product_codes > tbody:last-child').append('<tr><td>' + $('#code').val() + '</td><td>' + $('#description').val() + '</td></tr>');
                            $('#code').val('');
                            $('#description').val('');
                        },
                        error: function(msg) {

                        }
                    });

                    return false;
                });
</script>

Turns out in my blade template engine i was yielding my script twice (effectively including it twice.) 事实证明,在刀片服务器模板引擎中,我两次生成了脚本(实际上包括两次)。

The function works fine and only submits once now. 该功能运行正常,现在仅提交一次。

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

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