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

时间:2012-05-30 18:21:09

标签: jquery ajax loading

   $.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的显示,然后在加载图像后将其删除。在这里,我有这个代码来做到这一点,但这是直接错误。有没有人知道为什么或如何解决这个问题。提前谢谢!

3 个答案:

答案 0 :(得分:3)

您的ID选择器有两个哈希

请改为尝试:

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

答案 1 :(得分:1)

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

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";

答案 2 :(得分:0)

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

建议使用

.load():

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

然而,这也打破了我已经实现的代码,并且在IE中无法正常工作......不可原谅。

相关问题