为什么jQuery两次提交我的ajax表单? [英] Why does jquery submit my ajax form twice?

查看:112
本文介绍了为什么jQuery两次提交我的ajax表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提交我的表单时,如果不喜欢field1field2中包含的值,php将返回false.如果它确实喜欢那些字段,则它将返回true.如果用户提交表单,并且php返回false,则会出现警报.关闭警报窗口后,如果用户立即在这些字段中输入新(好的)数据并再次提交表单,则该表单将以某种方式提交两次.为什么?我该如何解决?

When my form is submitted php will return false if it doesn't like the values contained in field1 and field2. If it does like those fields, then it will return true. If a user submits the form and php returns false, then an alert appears. After closing the alert window, if the user immediately enters new (good) data into those fields and submits the form again, then the form is somehow submitted twice. Why? How can I fix this?

$("form#myForm").on('submit',function() 
{
    $.ajax(
    {
        type: "POST",
        url: 'myfile.php',
        dataType: 'html',
        data: 
        {
            field1:$("input[name=field1]").val(),
            field2:$("input[name=field2]").val()
        },
        success: function(data)
        {
            if(data == false) 
            {
                alert('hello world');
            } 
            else 
            {
                // stuff
            }
        }
    });
    return false;
});

推荐答案

2014年提出了相同的问题(

The same question was asked in 2014 (jquery ajax form submits twice).

e.preventDefault()本身可用于按钮和锚链接,但在提交表单时不起作用(与上述Nancy的代码相同).

e.preventDefault() on its own works for buttons and anchor links but didn't work for me when submitting a form (identical to Nancy 's code above).

我必须在我的Ajax发布之前添加e.stopImmediatePropagation();.这样就避免了两次提交ajax调用.

I had to add e.stopImmediatePropagation(); just before my ajax post. This stopped the ajax call from being submitted twice.

这篇关于为什么jQuery两次提交我的ajax表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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