在原型中,我可以用下面的代码显示“加载…”图像:

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

function showLoad () {
    ...
}

在jQuery中,我可以将服务器页面加载到一个元素中:

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

但是我如何附加一个加载旋转到这个命令,因为我在原型?


当前回答

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

 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/

其他回答

变体:我在主页的左上角有一个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() {}
});

你可以简单地将加载器图像分配给相同的标记,稍后你将使用Ajax调用加载内容:

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

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

还可以用图像标记替换span标记。

<script>
                $(window).on('beforeunload', function (e) {
                    $("#loader").show();
                });
                $(document).ready(function () {
                    $(window).load(function () {
                        $("#loader").hide();
                    });
                });
            </script>

<div id="loader">
                    <img src="../images/loader.png" 
                         style="width:90px;">
                </div>

有几种方法。我更喜欢的方法是在元素本身的ajaxStart/Stop事件上附加一个函数。

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

ajaxStart/Stop函数将在任何Ajax调用时触发。

更新:从jQuery 1.8开始,文档声明. ajaxstart /Stop只能被附加到文档中。这将把上面的代码片段转换为:

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

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; }