【问题标题】:How to avoid sending the form multiple times如何避免多次发送表单
【发布时间】:2014-02-24 08:58:21
【问题描述】:

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

我不明白这会如何发生。我尝试了很多双击或三次单击确定按钮,结果是

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

所以我需要你的建议。我该怎么做才能防止她再次发送同一个表单?

【问题讨论】:

  • 所以你的问题不在于意外的多次点击?因为如果我对您的理解正确,您无法重现相同的错误,而是多次单击,对吧?
  • 我无法重现它。这就是为什么我不明白她是怎么做到的,但这不是第一次投诉,我可以在系统中看到她确实有一些三排。

标签: javascript jquery ajax jquery-dialog


【解决方案1】:

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

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

【讨论】:

  • 好的,我试试这个。我希望 click() 函数仍然会运行到最后。此外,如果结果不正确,我必须再次绑定它,因为这可能只是一些验证警告。
  • 谢谢。所以我会让它这样,希望这能修复这个错误。
【解决方案2】:

你可以使用 one() 代替。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    • 1970-01-01
    • 2018-05-16
    相关资源
    最近更新 更多