Jquery Ajax 加载图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8761713/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery Ajax Loading image
提问by Kern Elliott
I would like to implement a loading image for my jquery ajax code (this is when the jquery is still processing) below is my code:
我想为我的 jquery ajax 代码实现一个加载图像(这是 jquery 仍在处理的时候)下面是我的代码:
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
alert("Success");
},
error: function (xhr, status) {
alert('Unknown error ' + status);
}
});
How can I implement a loading image in this code. Thanks
如何在此代码中实现加载图像。谢谢
回答by dknaack
Description
描述
You should do this using jQuery.ajaxStart
and jQuery.ajaxStop
.
您应该使用jQuery.ajaxStart
和来执行此操作jQuery.ajaxStop
。
- Create a div with your image
- Make it visible in
jQuery.ajaxStart
- Hide it in
jQuery.ajaxStop
- 用你的图像创建一个 div
- 使其可见
jQuery.ajaxStart
- 把它藏起来
jQuery.ajaxStop
Sample
样本
<div id="loading" style="display:none">Your Image</div>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
$(function () {
var loading = $("#loading");
$(document).ajaxStart(function () {
loading.show();
});
$(document).ajaxStop(function () {
loading.hide();
});
$("#startAjaxRequest").click(function () {
$.ajax({
url: "http://www.google.com",
// ...
});
});
});
</script>
<button id="startAjaxRequest">Start</button>
More Information
更多信息
回答by KMan
Try something like this:
尝试这样的事情:
<div id="LoadingImage" style="display: none">
<img src="" />
</div>
<script>
function ajaxCall(){
$("#LoadingImage").show();
$.ajax({
type: "GET",
url: surl,
dataType: "jsonp",
cache : false,
jsonp : "onJSONPLoad",
jsonpCallback: "newarticlescallback",
crossDomain: "true",
success: function(response) {
$("#LoadingImage").hide();
alert("Success");
},
error: function (xhr, status) {
$("#LoadingImage").hide();
alert('Unknown error ' + status);
}
});
}
</script>
回答by Maneksh Veetinal
Its a bit late but if you don't want to use a div specifically, I usually do it like this...
有点晚了,但是如果您不想专门使用 div,我通常会这样做...
var ajax_image = "<img src='/images/Loading.gif' alt='Loading...' />";
$('#ReplaceDiv').html(ajax_image);
ReplaceDiv is the div that the Ajax inserts too. So when it arrives, the image is replaced.
ReplaceDiv 也是 Ajax 插入的 div。所以当它到达时,图像被替换。
回答by ziria
Please note that: ajaxStart / ajaxStop is not working for ajax jsonp request (ajax json request is ok)
请注意:ajaxStart / ajaxStop 不适用于 ajax jsonp 请求(ajax json 请求是可以的)
I am using jquery 1.7.2 while writing this.
我在写这篇文章时使用 jquery 1.7.2。
here is one of the reference I found: http://bugs.jquery.com/ticket/8338
这是我找到的参考资料之一:http: //bugs.jquery.com/ticket/8338