如何避免多次发送表单

时间:2012-06-15 08:46:35

标签: javascript jquery ajax jquery-dialog

我在jquery对话框中有一个表单,它没有提交按钮。而是通过单击“确定”对话框按钮提交它。

所以当点击OK时,会发生这种情况:

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新行。所以看起来她设法在OK点击功能改变之前意外发送了3次表单。

我不知道这会怎么样。我已经尝试过双击或三键击OK按钮,结果是

  • 数据已发送一次
  • 表格未隐藏
  • 即使表单未被隐藏,单击确定后对话框关闭,没有任何内容再次发送

所以我需要你的建议。我该怎么办才能阻止她再次多次发送相同的表格?

2 个答案:

答案 0 :(得分:2)

我建议您在单击一次后取消绑定按钮事件监听器。这可能只是一个简单的解决方案,但我认为它会正常工作。

$('#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"); } }] );    
    });
});

修改

如果您希望重新绑定点击功能,如果表单的结果无效:

$('#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"); } }] );    
    });
}

答案 1 :(得分:1)

你可以使用一个()代替。

$("#submitButton").one("click", function() {
  //ajax code here
});