如何显示jQuery正在工作/等待/正在加载?
问题描述:
如何向用户显示加载图片和/或消息? 如果可能,我想知道如何使它成为灰色背景的全屏幕。有点像从一些画廊查看大图片(对不起,没有示例链接)。如何显示jQuery正在工作/等待/正在加载?
当前我添加一个CSS类,它具有图像和其他格式,但由于某种原因它不工作。 搜索结果会插入到div中。
HTML
<div id="searchresults"></div>
CSS
div.loading {
background-image: url('../img/loading.gif');
background-position: center;
width: 80px;
height: 80px;
}
JS
$(document).ready(function(){
$('#searchform').submit(function(){
$('#searchresults').addClass('loading');
$.post('search.php', $('#'+this.id).serialize(),function(result){
$('#searchresults').html(result);
});
$('#searchresults').removeClass('loading');
return false;
});
});
答
你的问题是,你在呼唤你发出Ajax调用后,它完成而不是之后。
你可以在ajax回调中做。 $.post
允许只提供success
回调:
jQuery.post(url, [ data ], [ success(data, textStatus, XMLHttpRequest) ], [ dataType ])
和加载图片应该在任何情况下被删除 - 更迭或失败,所以最好使用complete
回调$.ajax()
:
$('#searchform').submit(function(){
$('#searchresults').addClass('loading');
$.ajax({
type: 'POST',
url: 'search.php',
data: $('#'+this.id).serialize(),
success: function(result){
$('#searchresults').html(result);
},
complete: function() {
$('#searchresults').removeClass('loading');
}
});
return false;
});
查看更多有关“回调函数”中的回调部分$.ajax() docs
答
试试这个:
$("#contentLoading").ajaxSend(function(r, s) {
$(this).show();
$("#ready").hide();
});
$("#contentLoading").ajaxStop(function(r, s) {
$(this).hide();
$("#ready").show();
});
这将显示#contentLoading
这是我的进展gif
当我启动ajax并在ajax停止时隐藏它。