我在 jquery 对话框中有一个表单,它没有提交按钮。相反,它是通过单击“确定”对话框按钮提交的。
所以当点击确定时,会发生这种情况:
var data = $('#form').serialize();
$.post('page.php',data)
.success( function(result) {
// result might be description of an error or other problem, then I display error
...
// or ok, then I hide form and change OK button, so now it closes the dialog
...
myDialog.dialog( "option", "buttons", [{ text: ok, click: function() { $(this).dialog("close"); } }] );
});
它工作正常。表格的数据是行,它们随后显示在页面的表格中。但我多次收到报告,该用户提交了 N 行并获得了 3xN 新行。因此,在确定点击功能发生变化之前,她似乎不小心发送了 3 次表单。
我不知道这怎么可能发生。我试了很多次双击或三次单击确定按钮,结果是
- 数据发送一次
- 表格没有被隐藏
- 即使没有隐藏表单,在单击“确定”后对话框也会关闭并且不会再次发送任何内容
所以我需要你的建议。我该怎么做才能防止她再次多次发送相同的表格?
最佳答案
我建议您在单击一次按钮后取消绑定(bind)单击事件监听器。这可能只是一个简单的解决方案,但我认为它会很好地工作。
$('#submitButton').click(function(){
$(this).unbind('click');
var data = $('#form').serialize();
$.post('page.php',data).success( function(result) {
// result might be description of an error or other problem, then I display error
...
// or ok, then I hide form and change OK button, so now it closes the dialog
...
myDialog.dialog( "option", "buttons", [{ text: ok, click: function() {
$(this).dialog("close"); } }] );
});
});
编辑
如果表单结果无效,想重新绑定(bind)点击功能:
$('#submitButton').click(function(){
submitForm();
});
function submitForm();
$('#submitButton').unbind('click');
var data = $('#form').serialize();
$.post('page.php',data).success( function(result) {
// result might be description of an error or other problem, then I display error
// if result invalid rebind the click event
if(resultInvalid){
$('#submitButton').click(function(){
submitForm();
});
}
// or ok, then I hide form and change OK button, so now it closes the dialog
...
myDialog.dialog( "option", "buttons", [{ text: ok, click: function() {
$(this).dialog("close"); } }] );
});
}
关于javascript - 如何避免多次发送表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11047370/