Display loading GIF image while loading with AJAX

旧街凉风 提交于 2019-12-11 11:07:58

问题


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

I'm want to show display loading gif while image is loading and then remove it once image is loaded. Here I have this code to do that but, this is going straight to error. does anyone have any idea why or how to fix this. Thanks in advance!


回答1:


Your id selector has two hashes,

Try this instead:

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



回答2:


If you are getting to the error handler, the error is going to be related to the data that is being returned by the server. Try this as the error handler to get more information about what is going on (view the result in the browser's console):

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);
}

However, there is an easier way to pre-load an image. Try this:

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



回答3:


so I found out that you cannot load image as url in .ajax tag. thanks for the response but ##loading is just for the coldfusion tags

.load() is recommended like this:

 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);
                     }
          });

However, this also breaks my code I have implemented and doesn't work in IE...unfornately.



来源:https://stackoverflow.com/questions/10822038/display-loading-gif-image-while-loading-with-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!