Công việc của submitHandler là để gửi biểu mẫu, không phải đăng ký một hình thức nộp xử lý sự kiện.
Trình gửi được gọi khi sự kiện gửi biểu mẫu được kích hoạt, trong trường hợp của bạn thay vì gửi biểu mẫu bạn đã đăng ký trình xử lý gửi để khi biểu mẫu gửi sự kiện được kích hoạt lần đầu tiên biểu mẫu không được gửi. khi nó được kích hoạt lần thứ hai đầu tiên sự kiện gửi được xử lý bởi trình xác nhận hợp lệ thì trình xử lý mà bạn đã đăng ký được kích hoạt sẽ kích hoạt yêu cầu ajax.
Trong submitHandler bạn chỉ cần gửi yêu cầu ajax không có cần phải đăng ký xử lý sự kiện
$("#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);
});
}
});
Nguồn
2013-08-16 04:17:09
'** js từ trang khác **' nghĩa là gì? Vui lòng hiển thị đủ mã để tạo bản trình diễn ngắn gọn về sự cố. OP của bạn không nên dựa vào các liên kết bên ngoài để hiển thị tất cả các mã có liên quan. Plugin jQuery Validate chỉ yêu cầu _one_ click trừ khi bạn đã nhầm lẫn '.validate()' bên trong một trình xử lý 'click' hoặc' submit'. Và trong trường hợp của bạn, bạn đã nhầm lẫn một trình xử lý 'submit' bên trong' submitHandler' mặc định của plugin. Vì lời gọi lại 'submitHandler' của plugin đã nắm bắt được sự kiện gửi, trình xử lý' submit' đính kèm của bạn là thừa. – Sparky