【问题标题】:ajax "busy" indicator but only for longer requestsajax“忙”指示器,但仅适用于较长的请求
【发布时间】:2012-07-23 18:37:29
【问题描述】:

是否可以指定显示忙碌指示符的时间?

我的繁忙指示器代码非常简单:

jQuery.ajaxSetup( {
    beforeSend:function ()
    {
        jQuery( "#busy-indicator" ).show();
    }, complete:function ()
    {
        jQuery( "#busy-indicator" ).hide();
    }
} );

但通常 Ajax 请求比显示指示器更快,因此我想将它显示为至少需要 1 秒的请求,这可能吗?或者你知道怎么做吗?

【问题讨论】:

  • 在 beforeSend 回调中启动一个超时,一段时间后将显示您的加载器,在完成回调中取消超时并隐藏加载器。

标签: javascript jquery


【解决方案1】:

这就是诀窍:

var timeout; 
jQuery.ajaxSetup( {
    beforeSend:function ()
    {
        if (timeout) { clearTimeout(timeout); }
        timeout = setTimeout(function() {
            jQuery( "#busy-indicator" ).show(); 
        }, 1000);
    }, 
    complete:function ()
    {
        if (timeout) { clearTimeout(timeout); } 
        jQuery( "#busy-indicator" ).hide();
    }
});

【讨论】:

  • 经过一些测试后,我将添加到您的代码中的一件事:if (timeout) { clearTimeout(timeout); } 也在 beforeSend 的开头,连续 2 个 ajax 请求搞砸了一点超时 :)
【解决方案2】:
jQuery.ajaxSetup( {
    beforeSend:function ()
    {
        $( "#busy-indicator" ).stop(1,0).hide().delay(1000).show();
    }, 
    complete:function ()
    {
        $( "#busy-indicator" ).stop(1,0).hide();
    }
});

这不是也行吗?

【讨论】:

  • 这是一种更加 jqueryish 的方式来做到这一点:)。你能解释一下.stop(1,0)吗?
  • 好吧 .stop(1,0) 告诉 jQuery 清除该元素的动画队列,这样如果 ajax 函数被多次调用,动画就不会运行多次(动画之间有 1 秒的延迟)次。因此,在调用 ajax 之前,我们确保之前调用中没有其他动画正在运行,然后如果它可见,我们将隐藏指示器,然后延迟一秒显示它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多