javascript - 如何避免多次发送表单

标签 javascript jquery ajax jquery-dialog

我在 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/

相关文章:

javascript - 如何在 Javascript 中获取对表中同一行其他列上另一个对象的引用?

javascript - 清空标签时,内部的事件附加按钮是否会被垃圾收集?

jquery - 使用 jquery 将多个 .txt 文件合并为一个 html 表单选择下拉列表

ajax - 如何在谷歌浏览器中调试失败的ajax请求?

javascript - 关于 JavaScript promises 和 "then"语句的新手问题

javascript - 简化我的 jQuery 代码,它变得越来越庞大和冗余

javascript - 在 Angular Directive 参数中使用 HTML

javascript - 使用按钮更改文本输入

javascript - AJAX 联系表单在 Wordpress 中不起作用

ajax - 如何使用 Express/Jade 在 AJAX 中正确渲染局部 View 和加载 JavaScript 文件?