简体   繁体   English

如果if语句内的ajax表单在第一次失败后提交,为什么要提交两次?

[英]Why does an ajax form inside of an if statement submit twice if it is submitted after first failing the condition?

Consider the code below. 考虑下面的代码。 If myField1 does NOT equal myField2 , then the alert appears. 如果myField1不等于myField2 ,则显示警报。 When I click okay on the alert pop up my form is still there, with all of the fields still populated with the data I had previously entered. 当我在警报上单击“确定”时,弹出窗口仍然存在,所有字段仍填充有我先前输入的数据。 However, when I modify the fields so that myField1 DOES equal myField2 , and then submit the form it is actually submitted TWICE! 但是,当我修改字段以使myField1等于myField2 ,然后提交表单时,实际上是myField2提交! Why is this? 为什么是这样?

$(document).ready(function(){
$("#myForm").submit(function() {
    var myField1 = $('#myID1).val();
    var myField2 = $('#myID2).val();
    if(myField1 == myField2)
    {
        $.ajax({
            type: "POST",
            url: 'myFile.php',
            dataType: 'html',
            data: {myData:myField1,
                   myData2:myField2},
            success: function(data){
                alert(data);
            }
        });
        return false;
    }
    else
    {
        alert('These two fields are not equal!)
    }
});
});

Okay, so I found this on another question and it solves the problem: 好的,所以我在另一个问题上发现了这个问题,它解决了这个问题:

$('#myForm').unbind('submit').bind('submit',function() {
    // do stuff here...
});

By unbinding the event, then re-binding it, the form no longer submits twice. 通过取消绑定事件,然后重新绑定它,该表单不再提交两次。

Your submit event is going to fire the submit action of the form unless you prevent it from doing so. 您的submit事件将触发表单的submit操作,除非您阻止它这样做。 Running an AJAX call in does not prevent this from happening. 运行AJAX调用不会阻止这种情况的发生。 You need to stop this yourself. 您需要自己停止此操作。

You need: 你需要:

$("#myForm").submit(function(event) {
    event.preventDefault()
...

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

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