原型 我可以使用以下代码显示“正在加载...”图像:

var myAjax = new Ajax.Request( url, {method: 'get', parameters: pars, 
onLoading: showLoad, onComplete: showResponse} );

function showLoad () {
    ...
}

jQuery, ,我可以使用以下命令将服务器页面加载到元素中:

$('#message').load('index.php?pg=ajaxFlashcard');

但是如何像在原型中那样将加载微调器附加到此命令?

有帮助吗?

解决方案

有几种方法。我的首选方法是将函数附加到元素本身的 ajaxStart/Stop 事件。

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

每当您执行任何 Ajax 调用时,ajaxStart/Stop 函数都会触发。

更新:从 jQuery 1.8 开始,文档指出 .ajaxStart/Stop 应该只附加到 document. 。这会将上面的代码片段转换为:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

其他提示

对于 jQuery 我使用

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#loader').show();
  },
  complete: function(){
     $('#loader').hide();
  },
  success: function() {}
});

你可以只使用 jQuery 的 .ajax 函数并使用其选项 beforeSend 并定义一些函数,您可以在其中显示诸如加载器 div 之类的内容,并且在成功选项中您可以隐藏该加载器 div。

jQuery.ajax({
    type: "POST",
    url: 'YOU_URL_TO_WHICH_DATA_SEND',
    data:'YOUR_DATA_TO_SEND',
    beforeSend: function() {
        $("#loaderDiv").show();
    },
    success: function(data) {
        $("#loaderDiv").hide();
    }
});

您可以拥有任何旋转 Gif 图像。这里有一个网站,根据您的配色方案,它是一个很棒的 AJAX 加载器生成器: http://ajaxload.info/

您可以在 AJAX 调用之前将动画图像插入到 DOM 中,然后执行内联函数将其删除...

$("#myDiv").html('<img src="images/spinner.gif" alt="Wait" />');
$('#message').load('index.php?pg=ajaxFlashcard', null, function() {
  $("#myDiv").html('');
});

这将确保您的动画在后续请求中从同一帧开始(如果这很重要)。请注意,旧版本的 IE 可能 动画有困难。

祝你好运!

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

http://docs.jquery.com/Ajax/load#urldatacallback

如果您正在使用 $.ajax() 你可以使用这样的东西:

$.ajax({
        url: "destination url",
        success: sdialog,
        error: edialog,
        // shows the loader element before sending.
        beforeSend: function () { $("#imgSpinner1").show(); },
        // hides the loader after completion of request, whether successfull or failor.             
        complete: function () { $("#imgSpinner1").hide(); },             
        type: 'POST', dataType: 'json'
    });  

使用加载插件: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});

变体:我在主页的左上角有一个 id="logo" 的图标;当 ajax 工作时,旋转器 gif 会覆盖在顶部(具有透明度)。

jQuery.ajaxSetup({
  beforeSend: function() {
     $('#logo').css('background', 'url(images/ajax-loader.gif) no-repeat')
  },
  complete: function(){
     $('#logo').css('background', 'none')
  },
  success: function() {}
});

我最终对以下内容进行了两处更改 原回复.

  1. 从 jQuery 1.8 开始,ajaxStart 和 ajaxStop 只能附加到 document. 。这使得仅过滤某些 ajax 请求变得更加困难。苏...
  2. 切换到 ajax发送ajax完成 使得可以在显示微调器之前检查当前的 ajax 请求。

这是这些更改后的代码:

$(document)
    .hide()  // hide it initially
    .ajaxSend(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").show();
    })
    .ajaxComplete(function(event, jqxhr, settings) {
        if (settings.url !== "ajax/request.php") return;
        $(".spinner").hide();
    })

我也想为这个答案做出贡献。我一直在 jQuery 中寻找类似的东西,这就是我最终使用的。

我的加载旋转器来自 http://ajaxload.info/. 。我的解决方案基于这个简单的答案 http://christierney.com/2011/03/23/global-ajax-loading-spinners/.

基本上你的 HTML 标记和 CSS 看起来像这样:

<style>
     #ajaxSpinnerImage {
          display: none;
     }
</style>

<div id="ajaxSpinnerContainer">
     <img src="~/Content/ajax-loader.gif" id="ajaxSpinnerImage" title="working..." />
</div>

然后您的 jQuery 代码将如下所示:

<script>
     $(document).ready(function () {
          $(document)
          .ajaxStart(function () {
               $("#ajaxSpinnerImage").show();
          })
          .ajaxStop(function () {
               $("#ajaxSpinnerImage").hide();
          });

          var owmAPI = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&APPID=YourAppID";
          $.getJSON(owmAPI)
          .done(function (data) {
               alert(data.coord.lon);
          })
          .fail(function () {
               alert('error');
          });
     });
</script>

它是如此简单 :)

您可以简单地将加载程序图像分配给稍后将使用 Ajax 调用加载内容的同一标签:

$("#message").html('<span>Loading...</span>');

$('#message').load('index.php?pg=ajaxFlashcard');

您还可以用图像标签替换span标签。

除了为 ajax 事件设置全局默认值之外,您还可以设置特定元素的行为。也许仅仅改变他们的班级就足够了?

$('#myForm').ajaxSend( function() {
    $(this).addClass('loading');
});
$('#myForm').ajaxComplete( function(){
    $(this).removeClass('loading');
});

CSS 示例,使用微调器隐藏 #myForm:

.loading {
    display: block;
    background: url(spinner.gif) no-repeat center middle;
    width: 124px;
    height: 124px;
    margin: 0 auto;
}
/* Hide all the children of the 'loading' element */
.loading * {
    display: none;  
}

请注意,您必须使用异步调用才能使旋转器工作(至少这就是导致我的直到 ajax 调用之后才显示,然后在调用完成并删除旋转器时迅速消失的原因)。

$.ajax({
        url: requestUrl,
        data: data,
        dataType: 'JSON',
        processData: false,
        type: requestMethod,
        async: true,                         <<<<<<------ set async to true
        accepts: 'application/json',
        contentType: 'application/json',
        success: function (restResponse) {
            // something here
        },
        error: function (restResponse) {
            // something here                
        }
    });
$('#loading-image').html('<img src="/images/ajax-loader.gif"> Sending...');

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

           error:   function(jqXHR, textStatus, errorThrown) {
            var text =  "Error has occured when submitting the job: "+jqXHR.status+ " Contact IT dept";
           $('#loading-image').html('<span style="color:red">'+text +'  </span>');

            }
        });

我在 jQuery UI 对话框中使用了以下内容。(也许它可以与其他 ajax 回调一起使用?)

$('<div><img src="/i/loading.gif" id="loading" /></div>').load('/ajax.html').dialog({
    height: 300,
    width: 600,
    title: 'Wait for it...'
});

包含一个动画加载 gif,直到 ajax 调用完成时其内容被替换。

这对我来说是最好的方法:

jQuery:

$(document).ajaxStart(function() {
  $(".loading").show();
});

$(document).ajaxStop(function() {
  $(".loading").hide();
});

咖啡:

  $(document).ajaxStart ->
    $(".loading").show()

  $(document).ajaxStop ->
    $(".loading").hide()

文件: ajax启动, ajax停止

JavaScript

$.listen('click', '#captcha', function() {
    $('#captcha-block').html('<div id="loading" style="width: 70px; height: 40px; display: inline-block;" />');
    $.get("/captcha/new", null, function(data) {
        $('#captcha-block').html(data);
    }); 
    return false;
});

CSS

#loading { background: url(/image/loading.gif) no-repeat center; }

这是一个非常简单且智能的插件,用于特定目的:https://github.com/hekigan/is-loading

我这样做:

var preloaderdiv = '<div class="thumbs_preloader">Loading...</div>';
           $('#detail_thumbnails').html(preloaderdiv);
             $.ajax({
                        async:true,
                        url:'./Ajaxification/getRandomUser?top='+ $(sender).css('top') +'&lef='+ $(sender).css('left'),
                        success:function(data){
                            $('#detail_thumbnails').html(data);
                        }
             });

我想你是对的。这个方法太全局了...

然而,当 AJAX 调用对页面本身没有影响时,这是一个很好的默认值。(例如背景保存)。(您始终可以通过传递 "global":false 来关闭某个 ajax 调用 - 请参阅文档 jQuery

当 AJAX 调用旨在刷新页面的一部分时,我喜欢“加载”图像特定于刷新的部分。我想看看哪部分被刷新了。

想象一下,如果您可以简单地编写如下内容,那该多酷:

$("#component_to_refresh").ajax( { ... } ); 

这将在该部分显示“正在加载”。下面是我编写的一个函数,它也处理“加载”显示,但它特定于您在 ajax 中刷新的区域。

首先我来给大家展示一下如何使用

<!-- assume you have this HTML and you would like to refresh 
      it / load the content with ajax -->

<span id="email" name="name" class="ajax-loading">
</span>

<!-- then you have the following javascript --> 

$(document).ready(function(){
     $("#email").ajax({'url':"/my/url", load:true, global:false});
 })

这就是功能 - 一个基本的开始,您可以根据需要进行增强。它非常灵活。

jQuery.fn.ajax = function(options)
{
    var $this = $(this);
    debugger;
    function invokeFunc(func, arguments)
    {
        if ( typeof(func) == "function")
        {
            func( arguments ) ;
        }
    }

    function _think( obj, think )
    {
        if ( think )
        {
            obj.html('<div class="loading" style="background: url(/public/images/loading_1.gif) no-repeat; display:inline-block; width:70px; height:30px; padding-left:25px;"> Loading ... </div>');
        }
        else
        {
            obj.find(".loading").hide();
        }
    }

    function makeMeThink( think )
    {
        if ( $this.is(".ajax-loading") )
        {
            _think($this,think);
        }
        else
        {
            _think($this, think);
        }
    }

    options = $.extend({}, options); // make options not null - ridiculous, but still.
    // read more about ajax events
    var newoptions = $.extend({
        beforeSend: function()
        {
            invokeFunc(options.beforeSend, null);
            makeMeThink(true);
        },

        complete: function()
        {
            invokeFunc(options.complete);
            makeMeThink(false);
        },
        success:function(result)
        {
            invokeFunc(options.success);
            if ( options.load )
            {
                $this.html(result);
            }
        }

    }, options);

    $.ajax(newoptions);
};

如果您不想编写自己的代码,也有很多插件可以做到这一点:

如果您计划在每次发出服务器请求时都使用加载程序,则可以使用以下模式。

 jTarget.ajaxloader(); // (re)start the loader
 $.post('/libs/jajaxloader/demo/service/service.php', function (content) {
     jTarget.append(content); // or do something with the content
 })
 .always(function () {
     jTarget.ajaxloader("stop");
 });

这段代码特别使用了 jajaxloader 插件(我刚刚创建的)

https://github.com/lingtalfi/JAjaxLoader/

我的ajax代码看起来像这样,实际上,我刚刚注释掉了async:假线和微调器出现。

$.ajax({
        url: "@Url.Action("MyJsonAction", "Home")",
        type: "POST",
        dataType: "json",
        data: {parameter:variable},
        //async: false, 

        error: function () {
        },

        success: function (data) {
          if (Object.keys(data).length > 0) {
          //use data 
          }
          $('#ajaxspinner').hide();
        }
      });

我在 ajax 代码之前的函数中显示了微调器:

$("#MyDropDownID").change(function () {
        $('#ajaxspinner').show();

对于 Html,我使用了 font Awesome 类:

<i id="ajaxspinner" class="fas fa-spinner fa-spin fa-3x fa-fw" style="display:none"></i>

希望它能帮助某人。

您可以随时使用 阻止 UI jQuery 插件 它会为你做所有事情,甚至在 ajax 加载时阻止任何输入的页面。如果该插件似乎无法正常工作,您可以阅读有关使用它的正确方法 在这个答案中。 一探究竟。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top