How to cancel a jquery.load()?

前端 未结 7 1039
清酒与你
清酒与你 2020-11-29 07:30

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

7条回答
  •  我在风中等你
    2020-11-29 08:09

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

提交回复
热议问题