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

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

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

我发现这种方法的问题是,如果我在“正在加载...”中使用动画 gif div, ,它加载正常,但在提交表单时不会产生动画。

有没有更好的方法来消除弹跳并在等待表单结果(最终)加载时继续在页面上显示动画?­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

有帮助吗?

解决方案

如果您方便使用 jQuery,请附加一个在首次提交后禁用按钮的 click() 事件 -

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

之类的东西。

其他提示

使用 Prototype,您可以使用此代码来查看是否已提交任何表单,并在提交时禁用所有提交按钮:

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); 
    };

}

您可以尝试在输入(type=submit)元素上设置“禁用”标志,而不仅仅是更改样式。这应该完全关闭浏览器端的功能。

看: http://www.prototypejs.org/api/form/element#method-disable

使用 AJAX 提交表单,GIF 将呈现动画。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top