submitHandler 的工作是提交表单,而不是注册表单提交事件处理程序。
触发 formm submit 事件时调用 submitHandler ,在您的情况下,您注册了提交处理程序而不是提交表单,因此当第一次触发表单提交事件时,不会提交表单。当它第二次触发时,首先提交事件由验证器处理,然后触发您注册的处理程序,触发 ajax 请求。
在 submitHandler 中,您只需发送 ajax 请求,无需注册事件处理程序
$("#add-form").validate({
submitHandler: function (form) {
// setup some local variables
var $form = $(form);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "forms.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR) {
// log a message to the console
console.log("Hooray, it worked!");
alert("success awesome");
$('#add--response').html('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><strong>Well done!</strong> You successfully read this important alert message.</div>');
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown) {
// log the error to the console
console.error(
"The following error occured: " + textStatus, errorThrown);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
});