单击后禁用提交按钮以防止用户向服务器发送多个请求

时间:2014-04-02 10:20:54

标签: javascript jquery asp.net

我想阻止用户多次点击服务器按钮,导致多个类似的请求被发送到服务器。

按钮是ASP.Net按钮(Webforms)。网站上有很多页面,我不想为每个按钮编写一些代码。我想在所有按钮的主页面上进行此操作。

可能的解决方案是找到按钮并在单击后禁用它。像:

$("input[type='submit']").click(function(){
  $(this).attr('disabled','disabled');   
});    

此代码工作正常,但会覆盖按钮的上一个onclick事件。因此,按钮不会执行提交或任何其他要执行的任务。

另一个解决方案是禁用" onbeforesubmit"上的所有提交按钮。事件。它们将在回发后立即启用。这也不是一个好的解决方案,因为有一些按钮可以通过Ajax更新页面的一部分,并且在回发后它们无法重新启用ajax面板之外的其他按钮。

有没有办法找到点击的提交按钮并将其停用并允许它执行它的onclick事件?

3 个答案:

答案 0 :(得分:1)

我找到了答案。因为我使用asp.net服务器按钮,如果我在客户端onclick事件中禁用按钮,则不会提交Page。而是在第二次单击时禁用该按钮。在这种情况下,我可以确定该页面已经提交过一次:

        $("input[type='submit']").click(function (e) {
            if (e.target && Page_IsValid) {
                var attr = $(this).attr('submitting');
                if (typeof attr !== 'undefined' && attr !== false) { // If button has submitting attribute then do not submit it again.
                    $(this).prop('disabled', true);
                    $(this).removeAttr("submitting");
                    e.preventDefault();
                }
                else {
                    $(this).attr("submitting", "true"); // Add "submitting" attribute to prevent multiple submissions.
                }
            }
        });

答案 1 :(得分:0)

尝试使用 .one()

  

将处理程序附加到元素的事件。处理程序已执行   每个事件类型每个元素最多一次。

$("input[type='submit']").one('click',function(){
    $(this).prop('disabled',true);   
});  

此外,您应该使用.prop()代替.attr()来设置input的状态

答案 2 :(得分:0)

还是这个呢?

$("body").on("click", ".js-submit-button", function() {
        var $this = $(this);
        $this.prop("disabled", true);
        $this.closest("form").submit();
    });
相关问题