【发布时间】:2010-10-14 16:13:29
【问题描述】:
我一直在使用以下代码观察到一些奇怪的行为:
$.fn.submit_to_remote = function() {
// I use .each instead of the .submit directly so I can save
// the 'submitEnabled' variable separately for each form
jQuery.each($(this), function() {
$(this).submit(function() {
form = $(this);
if (form.data('submitEnabled') == false) { alert('disabled'); return false; }
form.data('submitEnabled', false);
$.ajax({type: 'POST', url: 'url', data: data, dataType: 'script',
success: function(script) {
alert('success')
}
})
return false;
})
})
}
$('.submit_to_remote').submit_to_remote();
因此,基本上,在表单上调用 submit_to_remote 时,它将禁用正常提交,然后发出 AJAX POST 请求。
奇怪的是表单被多次发布,因为“禁用”警报会显示。如您所见,我通过使用保存在表单对象上的“变量”来防止这种情况发生,并检查该变量以查看表单是否已提交。
经过进一步测试,罪魁祸首似乎是 AJAX 调用返回的脚本。让我解释一下我在做什么,这样会更清楚。
表单被发送到服务器,并返回一个脚本。该脚本再次显示表单,但这次显示某些字段的错误消息。请注意,表单已完全替换。
脚本在显示新表单后执行:
$('.submit_to_remote').submit_to_remote();
我必须这样做,否则,当您再次单击提交按钮时,表单会正常提交,没有 AJAX。
因此,假设用户提交表单并返回相应错误(未显示“禁用”警报)。然后他再次提交;这次“禁用”警报显示一次。现在他又提交了一次,这次警报显示了两次!等等……
所以看起来每次请求都会一次又一次地附加 .submit 回调,但为什么呢?
难道是通过使用 .html() 将原始表单保留为幽灵或其他东西?
谢谢!
PS:如果相关,这里是 $.ajax 调用返回的脚本:
replace_content_with = 'the form and other stuff here';
$('.page-content').html(replace_content_with);
$('.submit_to_remote').submit_to_remote();
【问题讨论】: