我了解 event.preventDefault()
和 event.stopImmediatePropagation()
。但这对我不起作用。就我而言,我有这样的 ajax 调用:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
var form = form2js('search_form', '.', true, function (node) {}, false);
var requestData = JSON.stringify(form, replacer);
var $formErrors = $('.search_form').find('.alert-danger');
event.preventDefault();
event.stopImmediatePropagation();
$.ajax({
type: 'POST',
contentType : "application/json",
url: '/fraud/template/testCreate',
data: requestData,
dataType: 'json',
success: function (data) {
$formErrors.text('');
//if no errors just reload
if (data === undefined || data.length === 0) {
location.reload();
}
else {
//else bind error messages
data.forEach(function(error) {
$('#new-' + error.field + '-error').text(error.defaultMessage);
})
}
}
});
});
我的问题是,ajax 调用被阻止的次数与我尝试输入数据的次数一样多。如果我输入了一次无效数据 - ajax 会被调用两次。如果是两次- 3次。这种行为的原因可能是什么?
最佳答案
每次发生此事件时:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
您绑定(bind)一个新的点击事件处理程序:
$(this).find('.modal-yes').click(function(){
因此,如果您 show.bs.modal
两次,那么就有两个 click
事件处理程序都提交 AJAX 请求。相反,只需将 click
事件处理程序一次绑定(bind)到目标可点击元素,而不是每次显示模式时都绑定(bind)它。
替换这个:
$('#templateConfirmDialog').on('show.bs.modal', function (event) {
$(this).find('.modal-yes').click(function(){
//...
});
});
这样:
$('#templateConfirmDialog').find('.modal-yes').click(function(){
//...
});
或者,如果该元素动态添加到 DOM,则:
$(document).on('click', '#templateConfirmDialog .modal-yes', function(){
//...
});
这样,在页面加载时只创建一个单击事件处理程序,而不是每次显示模式时添加一个新的处理程序。
关于javascript - 如果发生验证错误,Ajax 表单将发送两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47202050/