简体   繁体   中英

Ajax Image Preloader doesn't work

I was making a preloader using Ajax but It seems not to work. I want to load an image that if It's there the success does something -alert something-, but if It's not there just the error does another thing -alert another text-, but in this code It doesn´t matter if the image is found or not, both alerts happen no matter what, I mean if the image is found both alerts happen, but if I delete the photo both alerts happen as well, what could be the way to achieve this guys with ajax's complete and error? Thanks for any guideline in this one.

function preloadImages()
{   
 var $image = 'http://www.mysite/images/example.jpg';
 jQuery.ajax({
    url: $image,
            complete: function(){
         fileLoaded();
     },
    error: function(){
        errorLoading();
    }
 });    
}

function fileLoaded(){
alert('There is the image');
}

function errorLoading(){
alert('No image');
}

Thanks for any help in advance. Greetings.

Change complete to success

jQuery.ajax({
 url: $image,
     success: function(){
     fileLoaded();
 },
error: function(){
    errorLoading();
}
});

Fiddle

Try to figure out the error out of it as in this SO answer

error: function(xhr, status, error) {
  var err = eval("(" + xhr.responseText + ")");
  alert(err.Message);
}

If the image is in the site directory do it the following way

    var image = '../Images/Slider/1.jpg'; // give in the src of the image
    $.ajax({
        type: 'GET',
        url: image,
        success: function (bytes) {
            alert('in');
        },
        error: function () {
            alert('Error!!!')
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM