如何取消jquery.load()? [英] How to cancel a jquery.load()?

查看:496
本文介绍了如何取消jquery.load()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当load()在5秒内没有返回时,我想取消.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...

...超时处理:

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

...图片加载:

$('#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).

编辑:

另一种方式:我如何阻止。 load()方法在返回时调用它的回调函数?

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

推荐答案

如果你想要这样的自定义处理,你只需要不能使用jQuery.load()函数。您将不得不升级到jQuery.ajax(),我建议您使用它,因为您可以使用它做更多的事情,特别是如果您需要任何类型的错误处理,它将是必要的。

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.

使用jQuery.ajax的beforeSend选项并捕获xhr。然后你可以创建回调,它可以在超时后取消xhr,并在必要时回调。

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

这篇关于如何取消jquery.load()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆