Javascript 执行 $.ajax 时显示加载图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4684722/
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 13:37:02  来源:igfitidea点击:

Show loading image while $.ajax is performed

javascriptjquerycss

提问by Upvote

I am just wondering how to show an image that indicates that the async request is running. I use the following code to perform a async request:

我只是想知道如何显示指示异步请求正在运行的图像。我使用以下代码来执行异步请求:

$.ajax({
  url: uri,
  cache: false,
  success: function(html){
    $('.info').append(html);
  }
});

Any ideas?

有任何想法吗?

回答by Zack Bloom

You can, of course, show it before making the request, and hide it after it completes:

当然,您可以在发出请求之前显示它,并在它完成后隐藏它:

$('#loading-image').show();
$.ajax({
      url: uri,
      cache: false,
      success: function(html){
        $('.info').append(html);
      },
      complete: function(){
        $('#loading-image').hide();
      }
    });

I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:

我通常更喜欢将它绑定到全局 ajaxStart 和 ajaxStop 事件的更通用的解决方案,这样它就会显示所有 ajax 事件:

$('#loading-image').bind('ajaxStart', function(){
    $(this).show();
}).bind('ajaxStop', function(){
    $(this).hide();
});

回答by jEremyB

Use the ajax object's beforeSend and complete functions. It's better to show the gif from inside beforeSend so that all the behavior is encapsulated in a single object. Be careful about hiding the gif using the success function. If the request fails, you'll probably still want to hide the gif. To do this use the Complete function. It would look like this:

使用ajax对象的beforeSend和complete函数。最好在发送之前从内部显示 gif,以便所有行为都封装在单个对象中。使用成功函数隐藏 gif 时要小心。如果请求失败,您可能仍想隐藏 gif。为此,请使用 Complete 函数。它看起来像这样:

$.ajax({
    url: uri,
    cache: false,
    beforeSend: function(){
        $('#image').show();
    },
    complete: function(){
        $('#image').hide();
    },
    success: function(html){
       $('.info').append(html);
    }
});

回答by sumityadavbadli

HTML Code :

HTML代码:

<div class="ajax-loader">
  <img src="{{ url('guest/images/ajax-loader.gif') }}" class="img-responsive" />
</div>

CSS Code:

CSS 代码:

.ajax-loader {
  visibility: hidden;
  background-color: rgba(255,255,255,0.7);
  position: absolute;
  z-index: +100 !important;
  width: 100%;
  height:100%;
}

.ajax-loader img {
  position: relative;
  top:50%;
  left:50%;
}

JQUERY Code:

查询代码:

$.ajax({
  type:'POST',
  beforeSend: function(){
    $('.ajax-loader').css("visibility", "visible");
  },
  url:'/quantityPlus',
  data: {
   'productId':p1,
   'quantity':p2,
   'productPrice':p3},
   success:function(data){
     $('#'+p1+'value').text(data.newProductQuantity);
     $('#'+p1+'amount').text("? "+data.productAmount);
     $('#totalUnits').text(data.newNoOfUnits);
     $('#totalAmount').text("? "+data.newTotalAmount);
  },
  complete: function(){
    $('.ajax-loader').css("visibility", "hidden");
  }
});

}

回答by jEremyB

The "image" people generally show during an ajax call is an animated gif. Since there is no way to determine the percent complete of the ajax request, the animated gifs used are indeterminate spinners. This is just an image repeating over and over like a ball of circles of varying sizes. A good site to create your own custom indeterminate spinner is http://ajaxload.info/

人们通常在 ajax 调用期间显示的“图像”是 gif 动画。由于无法确定 ajax 请求的完成百分比,因此使用的动画 gif 是不确定的微调器。这只是一个像一个大小不一的圆球一样一遍又一遍地重复的图像。创建自己的自定义不确定微调器的好网站是http://ajaxload.info/

回答by The Terrible Child

I think this might be better if you have tons of $.ajax calls

我认为如果你有大量的 $.ajax 调用,这可能会更好

$(document).ajaxSend(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeIn(250);
});
$(document).ajaxComplete(function(){
    $(AnyElementYouWantToShowOnAjaxSend).fadeOut(250);
});

NOTE:

笔记:

If you use CSS. The element you want to shown while ajax is fetching data from your back-end code must be like this.

如果你使用 CSS。当 ajax 从后端代码中获取数据时,您想要显示的元素必须是这样的。

AnyElementYouWantToShowOnAjaxSend {
    position: fixed;
    top: 0;
    left: 0;
    height: 100vh; /* to make it responsive */
    width: 100vw; /* to make it responsive */
    overflow: hidden; /*to remove scrollbars */
    z-index: 99999; /*to make it appear on topmost part of the page */
    display: none; /*to make it visible only on fadeIn() function */
}

回答by matt

I've always liked the BlockUIplugin: http://jquery.malsup.com/block/

我一直很喜欢这个BlockUI插件:http: //jquery.malsup.com/block/

It allows you to block certain elements of a page, or the entire page while an ajax request is running.

它允许您在 ajax 请求运行时阻止页面的某些元素或整个页面。

回答by Vadim

Before your call either insert the loading image in a div/span somewhere and then on the success function remove that image. Alternatively you can set up a css class like loading that might look like this

在您调用之前,要么在某个 div/span 中插入加载图像,然后在成功函数中删除该图像。或者,您可以设置一个像加载这样的 css 类,它可能看起来像这样

.loading
{
    width: 16px;
    height: 16px;
    background:transparent url('loading.gif') no-repeat 0 0;
    font-size: 0px;
    display: inline-block;
}

And then assign this class to a span/div and clear it in the success function

然后将这个类分配给一个 span/div 并在成功函数中清除它

回答by Deepak Sharma

  1. Create a load element for e.g. an element with id = example_load.
  2. Hide it by default by adding style="display:none;".
  3. Now show it using jquery show element function just above your ajax.

    $('#example_load').show(); $.ajax({ type: "POST", data: {}, url: '/url', success: function(){ // Now hide the load element $('#example_load').hide(); } });

  1. 为例如具有 id = example_load 的元素创建加载元素。
  2. 默认情况下通过添加 style="display:none;" 来隐藏它。
  3. 现在使用 ajax 上方的 jquery show element 函数显示它。

    $('#example_load').show(); $.ajax({ type: "POST", data: {}, url: '/url', success: function(){ // Now hide the load element $('#example_load').hide(); } });

回答by Andy

something like this:

像这样:

$('#image').show();
$.ajax({
    url: uri,
    cache: false,
    success: function(html){
       $('.info').append(html);
       $('#image').hide();
    }
});

回答by Roshan Vishwakarma

You can add ajax start and complete event, this is work for when you click on button event

您可以添加 ajax 开始和完成事件,这适用于单击按钮事件时

 $(document).bind("ajaxSend", function () {
            $(":button").html('<i class="fa fa-spinner fa-spin"></i> Loading');
            $(":button").attr('disabled', 'disabled');
        }).bind("ajaxComplete", function () {
            $(":button").html('<i class="fa fa-check"></i> Show');
            $(":button").removeAttr('disabled', 'disabled');
        });