Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
914 views
in Technique[技术] by (71.8m points)

image - How to cancel a jquery.load()?

I'd like to cancel a .load() operation, when the load() does not return in 5 seconds. If it's so I show an error message like 'sorry, no picture loaded'.

What I have is...

...the timeout handling:

jQuery.fn.idle = function(time, postFunction){  
    var i = $(this);  
    i.queue(function(){  
        setTimeout(function(){  
            i.dequeue();
            postFunction();  
        }, time);  
    });
    return $(this); 
};

... initializing of the error message timeout:

var hasImage = false;

$('#errorMessage')
    .idle(5000, function() {

        if(!hasImage) {
            // 1. cancel .load()            
            // 2. show error message
        }
    });

... the image loading:

$('#myImage')
     .attr('src', '/url/anypath/image.png')
     .load(function(){
         hasImage = true;
         // do something...
      });

The only thing I could not figure out is how to cancel the running load() (if it's possible).

Edit:

Another way: How do I prevent the .load() method to call it's callback function when it's returning?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you want any custom handling such as this, you simply can't use the jQuery.load() function. You'll have to upgrade to jQuery.ajax(), which I recommend anyway since you can do so much more with it, especially if you need any kind of error handling, it will be necessary.

Use the beforeSend option for jQuery.ajax and capture the xhr. Then you can create callback which can cancel the xhr after your timeout, and the callbacks as necessary.

This code is not tested, but should get you started.

var enableCallbacks = true;
var timeout = null;
jQuery.ajax({
  ....
  beforeSend: function(xhr) {
    timeout = setTimeout(function() {
      xhr.abort();
      enableCallbacks = false;
      // Handle the timeout
      ...
    }, 5000);
  },
  error: function(xhr, textStatus, errorThrown) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle other (non-timeout) errors
  },
  success: function(data, textStatus) {
    clearTimeout(timeout);
    if (!enableCallbacks) return;
    // Handle the result
    ...
  }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...