0

我从 API 获取一些数据并且数据很大。我通过 AJAX 调用获取这些数据。

我的问题是我想显示加载器图像,直到获取所有数据。在我的 AJAX 成功函数中,我隐藏了加载程序图像。

这并不能解决我的问题:图像被隐藏但仍在获取数据。

我在谷歌上搜索并找到了.ajaxStart()and .ajaxStop(),但.ajaxStart()没有更多关于如何在其中使用 AJAX 的信息。

$(document).ajaxStart(function(){
  $.ajax(); // my ajax call
});

$(document).ajaxStart(function(){
    image.hide(); // hide my image
 });

但这并不能解决我的问题。有人可以告诉我怎么做吗?

4

2 回答 2

1

如果我正确理解了这个问题,那么您可能不太清楚它的用途$.ajaxStart()$.ajaxStop()用途。

如果您想在处理单个Ajax 调用时显示加载器图像,您可以这样做:

$('#loader').show();  // assuming the loader is e.g. <div id="loader">loading</div>

$.ajax( ... )         // your ajax call
    .done( function() {
        // when it's finished hide the loader
        $('#loader').hide();
    });

如果您想为每个Ajax 调用显示加载器,请使用$.ajaxStart()and $.ajaxStop()

$( document ).ajaxStart( function() {
    $('#loader').show();
}).ajaxStop( function() {
    $('#loader').hide();
});
于 2013-11-06T11:22:14.980 回答
1

单独编写您的$.ajax();并将以下内容保留为全局。

$(document).ajaxStart(function() {
    $('img').show();
}).ajaxStop(function() {
    $('img').hide();
});

如果您仍然觉得有任何困难,请尝试在callbacks.

$.ajax({
   // you ajax attributes 
   beforeSend: function(){
     $("img").show();
   },   
   success: function(data) {
     //handle the data that is being fetched
     $("img").hide();
   },
   error: function(error) {
     //handle the error
     $("img").hide();
   }
 });
于 2013-11-06T11:20:07.140 回答