且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Ajax 提交前的 jQuery 表单验证

更新时间:2023-11-21 11:17:52

您可以使用 submitHandler 选项.基本上将 $.ajax 调用放在此处理程序中,即使用验证设置逻辑将其反转.

You could use the submitHandler option. Basically put the $.ajax call inside this handler, i.e. invert it with the validation setup logic.

$('#form').validate({

    ... your validation rules come here,

    submitHandler: function(form) {
        $.ajax({
            url: form.action,
            type: form.method,
            data: $(form).serialize(),
            success: function(response) {
                $('#answers').html(response);
            }            
        });
    }
});

如果验证通过,jQuery.validate 插件将调用提交处理程序.

The jQuery.validate plugin will invoke the submit handler if the validation has passed.