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

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

function showLoad () {
    ...
}

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

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

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


当前回答

我是这样做的:

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(),你可以使用这样的东西:

$.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'
});

虽然设置名为“beforeSend”,但从jQuery 1.5开始,无论请求类型如何,都将调用“beforeSend”。例如,如果输入:'GET', .show()函数将被调用。

除了为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调用之前将动画图像插入到DOM中,并执行内联函数将其删除…

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

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

好运!

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

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

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