如何取消jquery.load()?

当load()在5秒内没有返回时,我想取消.load()操作。 如果是这样,我会显示一条错误消息,例如’抱歉,没有图片加载’。

我拥有的是……

…超时处理:

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

…初始化错误消息超时:

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

我唯一想知道的是如何取消正在运行的load()(如果可能的话)。

编辑:

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

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

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

此代码未经过测试,但应该让您入门。

 var enableCallbacks = true; var timeout = null; jQuery.ajax({ https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/.... beforeSend: function(xhr) { timeout = setTimeout(function() { xhr.abort(); enableCallbacks = false; // Handle the timeout https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... }, 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 https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... } }); 

你改写的第二个问题:
如何取消使用.load()方法创建的挂起回调函数?

您可以使用此“核”选项取消所有jquery回调:

 $('#myImage').unbind('load'); 

我认为最简单的方法是直接使用$.ajax 。 这样你可以开始超时,并从超时设置一个标志,ajax调用上的处理程序可以检查。 超时还可以显示消息或其他内容。

如果在加载JQuery之后加载此代码,则可以使用timeout参数调用.load()。

 jQuery.fn.load = function( url, params, callback, timeout ) { if ( typeof url !== "string" ) { return _load.call( this, url ); // Don't do a request if no elements are being requested } else if ( !this.length ) { return this; } var off = url.indexOf(" "); if ( off >= 0 ) { var selector = url.slice(off, url.length); url = url.slice(0, off); } // Default to a GET request var type = "GET"; // If the second parameter was provided if ( params ) { // If it's a function if ( jQuery.isFunction( params ) ) { if( callback && typeof callback === "number"){ timeout = callback; callback = params; params = null; }else{ // We assume that it's the callback callback = params; params = null; timeout = 0; } // Otherwise, build a param string } else if( typeof params === "number"){ timeout = params; callback = null; params = null; }else if ( typeof params === "object" ) { params = jQuery.param( params, jQuery.ajaxSettings.traditional ); type = "POST"; if( callback && typeof callback === "number"){ timeout = callback; callback = null; }else if(! timeout){ timeout = 0; } } } var self = this; // Request the remote document jQuery.ajax({ url: url, type: type, dataType: "html", data: params, timeout: timeout, complete: function( res, status ) { // If successful, inject the HTML into all the matched elements if ( status === "success" || status === "notmodified" ) { // See if a selector was specified self.html( selector ? // Create a dummy div to hold the results jQuery("
") // inject the contents of the document in, removing the scripts // to avoid any 'Permission Denied' errors in IE .append(res.responseText.replace(rscript, "")) // Locate the specified elements .find(selector) : // If not, just inject the full result res.responseText ); } if ( callback ) { self.each( callback, [res.responseText, status, res] ); } } }); return this; };

不确定您是否有兴趣覆盖任何“标准”JQuery函数,但这将允许您按照您描述的方式使用.load()。

我不认为你可以从这里到达 – 正如@Pointy所提到的,你需要访问XmlHttpRequest对象,这样你就可以访问它.abort()方法了。 为此,您需要.ajax() jQuery API将对象返回给您。

除非能够中止请求,另一种需要考虑的方法是将超时的知识添加到回调函数中。 你可以这两种方式 – 第一种:

 var hasImage = false; $('#errorMessage') .idle(5000, function() { if(!hasImage) { // 1. cancel .load() // 2. show error message // 3. Add an aborted flag onto the element(s) $('#myImage').data("aborted", true); } }); 

而你的回调:

 $('#myImage') .attr('src', '/url/anypath/image.png') .load(function(){ if($(this).data("aborted")){ $(this).removeData("aborted"); return; } hasImage = true; // do somethinghttps://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... }); 

或者你可以绕过这个特定function的空闲:

 $('#myImage') .attr('src', '/url/anypath/image.png') .data("start", (new Date()).getTime()) .load(function(){ var start = $(this).data("start"); $(this).removeData("start"); if(((new Date()).getTime() - start) > 5000) return; hasImage = true; // do somethinghttps://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... }); 

这两种方法都不是理想的,但我不认为你可以直接取消jQuery 1.4的加载 – 但是对于jQuery团队来说可能是一个不错的function请求。

$('#myImage').load(function(){https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/...})不是加载图像的函数调用,实际上是将回调绑定到onload 事件的简写。

因此,在其他答案中建议的.load() 方法中添加timeout参数将不起作用。

它认为你的两个选择是:

  1. 继续你正在追踪的路径,做一些像$('#myImage').attr('src', ''); 在超时后取消图像加载,或

  2. 找到一些方法来使用$.ajax( { https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... , timeout: 5000, https://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/...} ); 加载图像而不是让浏览器通过属性自动执行。

您可以在加载图像之前设置超时以及测试加载错误。

 function LoadImage(yourImage) { var imageTimer = setTimeout(function () { //image could not be loaded: alert('image load timed out'); }, 10000); //10 seconds $(yourImage).load(function (response, status, xhr) { if (imageTimer) { if (status == 'error') { //image could not be loaded: alert('failed to load image'); } else { //image was loaded: clearTimeout(imageTimer); //display your imagehttps://stackoverflow.com/questions/2813168/how-to-cancel-a-jquery-load/... } } }); }