使用AJAX加载时显示加载GIF图像

$.ajax({ url: "/image/productImages.jpg", timeout:5000, beforeSend: function(){ // Handle the beforeSend event $('##loading').show(); }, complete: function(){ // Handle the complete event $('##loading').hide(); }, success: function (data) { alert("image was added successfully"); }, error: function () { alert("There was an error. Image could not be added, please try again"); } }); 

我想在加载图像时显示加载gif的显示加载,然后在加载图像后将其删除。 在这里,我有这个代码来做到这一点,但这是直接错误。 有没有人知道为什么或如何解决这个问题。 提前致谢!

你的id选择器有两个哈希,

试试这个:

  $('#loading').show(); 

如果您要访问error handling程序,则错误将与服务器返回的数据相关。 尝试将此作为error handling程序以获取有关正在进行的操作的更多信息(在浏览器的控制台中查看结果):

 error: function (x,y,z) { alert("There was an error. Image could not be added, please try again"); console.log(x,y,z); //alert(x + "\n" + y + "\n" + z); } 

但是,有一种更简单的方法来预加载图像。 试试这个:

 $("#loading").show(); var img = new Image(); $(img).load(function(){ $("#loading").hide(); }); img.src = "/image/productImages.jpg"; 

所以我发现你无法在.ajax标签中将图片加载为url。 感谢您的回复,但## loading仅适用于coldfusion标签

建议使用.load():

  var img = $("").attr('src', 'http://sofzh.miximages.com/jquery/f') .load(function() { if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { alert('broken image!'); } else { $("#something").append(img); } }); 

但是,这也打破了我已经实现的代码,并且在IE中无法正常工作……这是不合情理的。