Javascript 如何在ajax请求期间显示处理动画/微调器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4901537/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:40:10  来源:igfitidea点击:

How to show processing animation / spinner during ajax request?

javascriptjqueryajaxdjangospinner

提问by Will Curran

I want a basic spinner or processing animation while my AJAX POST is processing. I'm using JQuery and Python. I looked at the documentation but can't figure out exactly where to put the ajaxStart and ajaxStop functions.

我想要一个基本的微调器或处理动画,而我的 AJAX POST 正在处理。我正在使用 JQuery 和 Python。我查看了文档,但无法确定将 ajaxStart 和 ajaxStop 函数放在哪里。

Here is my js:

这是我的js:

    <script type="text/javascript">
      $(function() {  
        $('.error').hide();  
        $("#checkin-button").click(function() { 
          var mid = $("input#mid").val();
          var message = $("textarea#message").val();
          var facebook = $('input#facebook').is(':checked');
          var name = $("input#name").val();
          var bgg_id = $("input#bgg-id").val();
          var thumbnail = $("input#thumbnail").val();
          var dataString = 'mid='+mid+'&message='+message+'&facebook='+facebook+'&name='+name+'&bgg_id='+bgg_id+'&thumbnail='+thumbnail;  
          $.ajax({  
            type: "POST",  
            url: "/game-checkin",  
            data: dataString,  
            success: function(badges) {  
            $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");  
            $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");  
            $.each(badges, function(i,badge) {
              $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='"+badge.image_url+"'><span class='badge-title'>"+badge.name+"</span></p>");  
            });
          }
       });
       return false;
     });  
    });
  </script>

回答by Mandrake

$.ajax({
  type: "POST",
  url: "/game-checkin",
  data: dataString,
  beforeSend: function () {
    // ... your initialization code here (so show loader) ...
  },
  complete: function () {
    // ... your finalization code here (hide loader) ...
  },
  success: function (badges) {
    $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
    $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
    $.each(badges, function (i, badge) {
      $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
    })
  }
});

http://api.jquery.com/jQuery.ajax/:

http://api.jquery.com/jQuery.ajax/

Here are the callback hooks provided by $.ajax():

beforeSend callback is invoked; it receives the jqXHR object and the settings map as parameters. error callbacks are invoked, in the order they are registered, if the request fails. They receive the jqXHR, a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: "abort", "timeout", "No Transport". dataFilter callback is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType, and must return the (possibly altered) data to pass on to success. success callbacks are then invoked, in the order they are registered, if the request succeeds. They receive the returned data, a string containing the success code, and the jqXHR object. complete callbacks fire, in the order they are registered, when the request finishes, whether in failure or success. They receive the jqXHR object, as well as a string containing the success or error code.

以下是 $.ajax() 提供的回调钩子:

beforeSend 回调被调用;它接收 jqXHR 对象和设置映射作为参数。如果请求失败,则按照注册顺序调用错误回调。它们接收 jqXHR、指示错误类型的字符串和异常对象(如果适用)。一些内置错误会提供一个字符串作为异常对象:“abort”、“timeout”、“No Transport”。成功接收到响应数据后立即调用 dataFilter 回调。它接收返回的数据和 dataType 的值,并且必须返回(可能已更改的)数据以传递成功。如果请求成功,则按照注册顺序调用成功回调。它们接收返回的数据、包含成功代码的字符串和 jqXHR 对象。完整的回调触发,按照它们注册的顺序,当请求完成时,无论是失败还是成功。它们接收 jqXHR 对象,以及包含成功或错误代码的字符串。

Note the beforeSendand complete method additions to the code.

请注意beforeSend代码中添加的完整方法。

Hope that helps.

希望有帮助。

回答by Julian Aubourg

If you're using jQuery 1.5 you could do that nicely, unobtrusively and generically with a prefilter. Let's make a very simple plugin for this:

如果您使用的是 jQuery 1.5,您可以使用prefilter很好地、不引人注目地和一般地做到这一点。让我们为此制作一个非常简单的插件:

(function($) {

    var animations = {};

    $.ajaxPrefilter(function( options, _, jqXHR ) {
        var animation = options.animation && animations[ options.animation ];
        if ( animation ) {
            animation.start();
            jqXHR.then( animation.stop, animation.stop );
        }
    });

    $.ajaxAnimation = function( name, object ) {
        if ( object ) {
            animations[ name ] = object;
        }
        return animations[ name ];
    };

})( jQuery );

You install an animation as follows:

您可以按如下方式安装动画:

jQuery.ajaxAnimation( "spinner" , {
    start: function() {
        // code that starts the animation
    }
    stop: function() {
        // code that stops the animation
    }
} );

then, you specify the animation in your ajax options:

然后,您在 ajax 选项中指定动画:

jQuery.ajax({
    type: "POST",
    url: "/game-checkin",
    data: dataString,
    animation: "spinner",
    success: function() {
        // your success code here
    }
});

and the prefilter will ensure the "spinner" animation is started and stopped when needed.

预过滤器将确保“微调”动画在需要时启动和停止。

Of course, that way, you can have alternative animations installed and select the one you need per request. You can even set a default animation for all requests using ajaxSetup:

当然,这样,您可以安装替代动画并根据请求选择您需要的动画。您甚至可以使用 ajaxSetup 为所有请求设置默认动画:

jQuery.ajaxSetup({
    animation: "spinner"
});

回答by Always Sunny

you can set global ajax loading icon handler using here #ajxLoader takes your loading icon

您可以使用此处设置全局 ajax 加载图标处理程序 #ajxLoader 使用您的加载图标

   $( document ).ajaxStart(function() {
        $("#ajxLoader").fadeIn();
    });

    $( document ).ajaxComplete(function() {
        $("#ajxLoader").fadeOut();
    });

回答by Chris Sobolewski

The best method I have found, assuming you are populating a present but empty field is to have a .loadingclass defined with background-image: url('images/loading.gif')in your CSS. You can then add and remove the loading class as necessary with jQuery.

我发现的最好方法,假设您正在填充一个存在但为空的字段,那就是在您的 CSS 中.loading定义一个类background-image: url('images/loading.gif')。然后,您可以根据需要使用 jQuery 添加和删除加载类。

回答by Craig

The AJAX process starts when you run the $.ajax()method, and it stops when the 'complete' callback is run. So, start your processing imagery/notification right before the $.ajax()line, and end it in the 'complete' callback.

AJAX 进程在您运行该$.ajax()方法时启动,并在运行“完成”回调时停止。因此,在该$.ajax()行之前开始处理图像/通知,并在“完成”回调中结束。

ajaxStartand ajaxStophandlers can be added to any elements, and will be called whenever ajax requests start or stop (if there are concurrent instances, start only gets called on the first one, stop on the last to go). So, it's just a different way of doing global notification if you had, for example, a status spinner somewhere on the page that represents any and all activity.

ajaxStartajaxStop处理程序可以添加到任何元素,并且将在 ajax 请求开始或停止时调用(如果有并发实例,则仅在第一个调用 start ,在最后一个调用时停止)。因此,这只是一种不同的全局通知方式,例如,如果您在页面上的某处有一个状态微调器代表任何和所有活动。

回答by Idered

$(function() {
        $('.error').hide();
        $("#checkin-button").click(function() {
                var mid = $("input#mid").val();
                var message = $("textarea#message").val();
                var facebook = $('input#facebook').is(':checked');
                var name = $("input#name").val();
                var bgg_id = $("input#bgg-id").val();
                var thumbnail = $("input#thumbnail").val();
                var dataString = 'mid=' + mid + '&message=' + message + '&facebook=' + facebook + '&name=' + name + '&bgg_id=' + bgg_id + '&thumbnail=' + thumbnail;
                $.ajax({
                        type : "POST",
                        url : "/game-checkin",
                        data : dataString,
                        beforeSend : function() {
                         $('#preloader').addClass('active');
                        },
                        success : function(badges) {
                            $('#preloader').removeClass('active');
                            $('#checkin-form').html("<div id='message'></div><div id='badges'></div>");
                            $('#message').html("<h2><img class=\"check-mark\" src=\"/static/images/check-mark.png\"/>You are checked in!</h2>");
                            $.each(badges, function(i, badge) {
                                    $('#badges').append("<h2>New Badge!</h2><p><img class='badge' src='" + badge.image_url + "'><span class='badge-title'>" + badge.name + "</span></p>");
                                });
                        },
                        complete : function() {
                            $('#preloader').removeClass('active');                      
                        }
                    });
                return false;
            });
    });


#preloader{
 background: url(staticpreloader.gif);
}
.active {
 background: url(activepreloader.gif);
}

回答by SKFox

I wrote a blog postabout how to do this on a generic document level.

我写了一篇关于如何在通用文档级别执行此操作的博客文章

// prepare the form when the DOM is ready 
$(document).ready(function() { 

  // Setup the ajax indicator
  $('body').append('<div id="ajaxBusy"><p><img src="images/loading.gif"></p></div>');

  $('#ajaxBusy').css({
    display:"none",
    margin:"0px",
    paddingLeft:"0px",
    paddingRight:"0px",
    paddingTop:"0px",
    paddingBottom:"0px",
    position:"absolute",
    right:"3px",
    top:"3px",
     width:"auto"
  });
});

// Ajax activity indicator bound to ajax start/stop document events
$(document).ajaxStart(function(){ 
  $('#ajaxBusy').show(); 
}).ajaxStop(function(){ 
  $('#ajaxBusy').hide();
});