提交网络表单时消除点击

时间:2020-03-06 14:23:59  来源:igfitidea点击:

与我们连接的后端系统编写不良,在处理我们产生的负载时遇到了麻烦。当他们解决他们的负载问题时,我们正在尝试减少我们正在生成的任何其他负载,其中之一是,即使另一个提交来自同一用户,后端系统仍会继续尝试为表单提交提供服务。

我们注意到的一件事是用户双击表单提交按钮。我需要消除这些点击,并阻止再次提交表单。
我的方法(使用Prototype)在表单上放置一个" onSubmit",该函数调用以下函数,该函数隐藏表单提交按钮并显示" loading ..." div。

function disableSubmit(id1, id2) {
    $(id1).style.display = 'none';
    $(id2).style.display = 'inline';
}

我发现这种方法的问题是,如果我在" diving"中使用动画gif,它会很好地加载,但在提交表单时不会激活。

有没有更好的方法来执行此反跳操作并在等待表单结果(最终)加载时继续在页面上显示动画?

解决方案

我们可以尝试在input(type = submit)元素上设置" disabled"标志,而不只是更改样式。那应该完全关闭浏览器端的。

请参阅:http://www.prototypejs.org/api/form/element#method-disable

如果我们方便使用jQuery,请添加一个click()事件,该事件会在首次提交后禁用按钮-

$('input[type="submit"]').click(function(event){
 event.preventDefault();
 this.click(null);
});

之类的东西。

使用原型,我们可以使用此代码查看是否已提交任何表单,并在执行以下操作时禁用所有提交按钮:

document.observe( 'dom:loaded', function() { // when document is loaded
    $$( 'form' ).each( function( form ) { // find all FORM elements in the document
        form.observe( 'submit', function() {  // when any form is submitted
            $$( 'input[type="submit"]' ).invoke( 'disable' );  // disable all submit buttons
        } );
    } );
} );

这对双击提交按钮的用户有帮助。但是,仍然可以通过其他任何方式提交表单(例如,在文本字段上按Enter键)。为防止这种情况,我们必须在第一个表单提交之后开始监视任何表单提交并停止它:

document.observe( 'dom:loaded', function() {
    $$( 'form' ).each( function( form ) {
        form.observe( 'submit', function() {
            $$( 'input[type="submit"]' ).invoke( 'disable' );
            $$( 'form' ).observe( 'submit', function( evt ) { // once any form is submitted
                evt.stop(); // prevent any other form submission
            } );
        } );
    } );
} );

上面所有好的建议。如果我们真的想像我们所说的那样"去抖动",那么我对此有很好的功能。有关更多详细信息,请访问unscriptable.com

var debounce = function (func, threshold, execAsap) {

    var timeout;

    return function debounced () {
        var obj = this, args = arguments;
        function delayed () {
            if (!execAsap)
                func.apply(obj, args);
            timeout = null; 
        };

        if (timeout)
            clearTimeout(timeout);
        else if (execAsap)
            func.apply(obj, args);

        timeout = setTimeout(delayed, threshold || 100); 
    };

}

使用AJAX提交表单,然后GIF会进行动画处理。