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

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

function showLoad () {
    ...
}

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

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

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


当前回答

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

https://github.com/keithhackbarth/jquery-loading http://plugins.jquery.com/project/loading

其他回答

有几种方法。我更喜欢的方法是在元素本身的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();
  });

使用加载插件: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() {}
});

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

https://github.com/keithhackbarth/jquery-loading http://plugins.jquery.com/project/loading

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

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

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

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