How to call .ajaxStart() on specific ajax calls

前端 未结 10 828
孤独总比滥情好
孤独总比滥情好 2020-11-28 03:47

I have some ajax calls on the document of a site that display or hide a progress bar depending on the ajax status

  $(document).ajaxStart(function(){ 
              


        
10条回答
  •  孤城傲影
    2020-11-28 04:26

    Unfortunately, ajaxStart event doesn't have any additional information which you can use to decide whether to show animation or not.

    Anyway, here's one idea. In your ajaxStart method, why not start animation after say 200 milliseconds? If ajax requests complete in 200 milliseconds, you don't show any animation, otherwise you show the animation. Code may look something like:

    var animationController = function animationController()
    {
        var timeout = null;
        var delayBy = 200; //Number of milliseconds to wait before ajax animation starts.
    
        var pub = {};
    
        var actualAnimationStart = function actualAnimationStart()
        {
            $('#ajaxProgress').show();
        };
    
        var actualAnimationStop = function actualAnimationStop()
        {
            $('#ajaxProgress').hide();
        };
    
        pub.startAnimation = function animationController$startAnimation() 
        { 
            timeout = setTimeout(actualAnimationStart, delayBy);
        };
    
        pub.stopAnimation = function animationController$stopAnimation()
        {
            //If ajax call finishes before the timeout occurs, we wouldn't have 
            //shown any animation.
            clearTimeout(timeout);
            actualAnimationStop();
        }
    
        return pub;
    }();
    
    
    $(document).ready(
        function()
        {
            $(document).ajaxStart(animationController.startAnimation);
            $(document).ajaxStop(animationController.stopAnimation);
        }
     );
    

提交回复
热议问题