jQuery Validation插件:在对servlet进行ajax调用时,submitHandler不会阻止提交时的默认值 - 返回false不能正常工作

时间:2022-12-01 09:04:16

I have a simple form that uses jquery and a servlet. The jquery makes an ajax call to the servlet, the servlet makes some server side calculations, then displays the results on the same page via jQuery. I don't want the form to do a default submit (and go to the servlet) because I want to stay on the same page and display results dynamically. It works exactly how I want it to as is:

我有一个使用jquery和servlet的简单表单。 jquery对servlet进行ajax调用,servlet进行一些服务器端计算,然后通过jQuery在同一页面上显示结果。我不希望表单执行默认提交(并转到servlet),因为我想保持在同一页面上并动态显示结果。它的工作方式与我想要的完全一致:

HTML:

<form name="form1" action="FormHandler1" method="POST" class="stats-form">
    <input class="stats-input" id="number0" type="text" name="number0">
    <input id="number1" type="text" name="number1">
    <input id="number2" type="text" name="number2">
    <input id="number3" type="text" name="number3">
    <input type="submit" value="Calculate" class="calculate-stats" name="stats-submit">
</form>

jQuery:

form.submit (function(event) {
    $.ajax({
        type: form.attr("method"), // use method specified in form attributes
        url: form.attr("action"), // use action specified in form attributes (servlet)
        data: form.serialize(), // encodes set of form elements as string for submission
        success: function(data) {
            // get response form servlet and display on page via jquery 
        }
    });
    event.preventDefault(); // stop form from redirecting to java servlet page
});

Now, I wanted to add form validation, since the servlet expects decimal numbers to do it's calculations. The user should only be allowed to enter numbers, no other characters. To do this I adopted the popular jQuery Validation plugin.

现在,我想添加表单验证,因为servlet需要十进制数来进行计算。只允许用户输入数字,不允许输入其他字符。为此,我采用了流行的jQuery Validation插件。

The validation works as expected, but to make my ajax call to the servlet I have to use the submitHandler jQuery Validation provides, instead of the jQuery submit method shown above. When I use the validation submitHandler, the default action of the form on submit is executed, going to the servlet page instead of staying on the same page to display my results dynamically in jQuery. I have to pass the formHandler a form, instead of an event like before, which allowed me to prevent the default action. The only option is to return false, but it doesn't work. I've been trying to figure this out for the past two days, and have pretty much exhausted my google-fu. Here is the new code giving me grief:

验证按预期工作,但是要对servlet进行ajax调用,我必须使用submitHandler jQuery Validation提供,而不是上面显示的jQuery submit方法。当我使用验证submitHandler时,执行表单上的默认操作,进入servlet页面而不是停留在同一页面上以在jQuery中动态显示我的结果。我必须传递formHandler一个表单,而不是之前的事件,这允许我阻止默认操作。唯一的选择是返回false,但它不起作用。在过去的两天里,我一直试图解决这个问题,而且我的google-fu已经筋疲力尽了。这是给我悲伤的新代码:

form.validate({
       rules: {
            number0: ruleSet,
            number1: ruleSet,
            number2: ruleSet,
            number3: ruleSet,
        },
        submitHandler: function (form) {

            $.ajax({
                type: "POST",
                url: form.attr("action"),
                data: form.serialize(),
                success: function () {
                    // get response from servlet and display on page via jQuery 
                }
            });
            return false; // required to block normal submit ajax used
        }
 });

Any help would be appreciated, I'd like to use this neat jQuery form validation, but I may just write my own jQuery validation from scratch so that I can use the form submit method that I already have working.

任何帮助将不胜感激,我想使用这个简洁的jQuery表单验证,但我可能只是从头开始编写自己的jQuery验证,以便我可以使用我已经工作的表单提交方法。

4 个解决方案

#1


6  

By the time the submit event has fired it's too late to prevent the form from submitting. You should bind to the click event on the submit button and use event.preventDefault() to stop it from submitting. If your validation routine completes successfully you can use $.serialize() and $.submit() to manually submit the form.

当提交事件被触发时,要阻止表单提交已经太晚了。您应该绑定到提交按钮上的click事件,并使用event.preventDefault()来阻止它提交。如果验证例程成功完成,您可以使用$ .serialize()和$ .submit()手动提交表单。

#2


2  

To resolve the problem, I validate the form separately my form submit handler. I simply put a check for validity inside the form submit, executing the ajax call only if true. This allows the action of the submit event to be handled (preventDefault()) regardless if the ajax call is made or not.

要解决此问题,我将表单单独验证表单提交处理程序。我只是在表单提交中检查有效性,只有在执行时才执行ajax调用。这允许处理提交事件的动作(preventDefault()),无论是否进行了ajax调用。

form.validate({
    rules: {
        number0: ruleSet,
        number1: ruleSet,
        number2: ruleSet,
        number3: ruleSet,
    }
});

form.submit (function(event) {
    if (form.valid())
    {
        $.ajax({
            type: form.attr("method"), // use method specified in form attributes
            url: form.attr("action"), // use action specified in form attributes
            data: form.serialize(), // encodes set of form elements as string for submission
            success: function(data) {
                // get response from servlet and display on page via jQuery 
            }
        });
    }
    event.preventDefault(); // stop form from redirecting to java servlet page
});

#3


2  

You can have event as the second parameter of submitHandler and can do preventDefault there itself.

您可以将event作为submitHandler的第二个参数,并且可以自己执行preventDefault。

submitHandler: function (form, event) {
    event.preventDefault();
    // your remaining code goes below this.
}

#4


-1  

$('#post_form_jason_data').click(function() {
$('#myform').validate({ 
    rules: {
        txtwtrt: {
            required: true
           // email: true
        },
        tax_name: {
            required: true,
            minlength: 5
        },
    tax_rate: {
            required: true
            //minlength: 5
        }
    }
});
alert('insert the value');
if (('#myform').valid()){


        $.ajax({
            url: "swt_tax_add.html",
            type: 'POST',
            data : $('#myform').serialize(),                
            success: function(msg) {
                window.location.href='swt_tax/?st=1';
                $('#message').html(msg);            

            }

        });
    }

        return false;
    });

#1


6  

By the time the submit event has fired it's too late to prevent the form from submitting. You should bind to the click event on the submit button and use event.preventDefault() to stop it from submitting. If your validation routine completes successfully you can use $.serialize() and $.submit() to manually submit the form.

当提交事件被触发时,要阻止表单提交已经太晚了。您应该绑定到提交按钮上的click事件,并使用event.preventDefault()来阻止它提交。如果验证例程成功完成,您可以使用$ .serialize()和$ .submit()手动提交表单。

#2


2  

To resolve the problem, I validate the form separately my form submit handler. I simply put a check for validity inside the form submit, executing the ajax call only if true. This allows the action of the submit event to be handled (preventDefault()) regardless if the ajax call is made or not.

要解决此问题,我将表单单独验证表单提交处理程序。我只是在表单提交中检查有效性,只有在执行时才执行ajax调用。这允许处理提交事件的动作(preventDefault()),无论是否进行了ajax调用。

form.validate({
    rules: {
        number0: ruleSet,
        number1: ruleSet,
        number2: ruleSet,
        number3: ruleSet,
    }
});

form.submit (function(event) {
    if (form.valid())
    {
        $.ajax({
            type: form.attr("method"), // use method specified in form attributes
            url: form.attr("action"), // use action specified in form attributes
            data: form.serialize(), // encodes set of form elements as string for submission
            success: function(data) {
                // get response from servlet and display on page via jQuery 
            }
        });
    }
    event.preventDefault(); // stop form from redirecting to java servlet page
});

#3


2  

You can have event as the second parameter of submitHandler and can do preventDefault there itself.

您可以将event作为submitHandler的第二个参数,并且可以自己执行preventDefault。

submitHandler: function (form, event) {
    event.preventDefault();
    // your remaining code goes below this.
}

#4


-1  

$('#post_form_jason_data').click(function() {
$('#myform').validate({ 
    rules: {
        txtwtrt: {
            required: true
           // email: true
        },
        tax_name: {
            required: true,
            minlength: 5
        },
    tax_rate: {
            required: true
            //minlength: 5
        }
    }
});
alert('insert the value');
if (('#myform').valid()){


        $.ajax({
            url: "swt_tax_add.html",
            type: 'POST',
            data : $('#myform').serialize(),                
            success: function(msg) {
                window.location.href='swt_tax/?st=1';
                $('#message').html(msg);            

            }

        });
    }

        return false;
    });