How to set timeout on $.ajax request and redo it if it takes too long?
有人可以告诉我一个关于为我的$ .ajax请求设置超时的实际示例,并在第一个请求超时的情况下重做整个请求,我已经阅读了文档并且没有得到它。 我将不胜感激任何帮助。
这是我的$ .ajax请求。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | $.ajax({ url: '<?php bloginfo('template_directory'); ?>/ajax/product.php', type: 'get', data: {product_id : product_id}, beforeSend: function(){ $('#details').html(''); }, success: function(data){ $('.iosSlider').fadeOut('fast'); thisprod.addClass('current'); $('#details').css({opacity: 0}).html(data).stop().animate({left: 0, opacity: 1}, 800); } }); return false; |
ajax函数采用超时参数,您可以在出现错误时检查状态。
1 2 3 4 5 6 7 8 9 10 11 12 13 | var call =function(){ $.ajax({ url: '<?php bloginfo('template_directory'); ?>/ajax/product.php', type: 'get', timeout: 400, ... error: function(x, textStatus, m) { if (textStatus=="timeout") { call(); } } }); }; |
你可能想要做一些更聪明的事情以避免永久性的电话......
从文档:
Set a timeout (in milliseconds) for the request. This will override
any global timeout set with $.ajaxSetup(). The timeout period starts
at the point the $.ajax call is made; if several other requests are in
progress and the browser has no connections available, it is possible
for a request to time out before it can be sent. In jQuery 1.4.x and
below, the XMLHttpRequest object will be in an invalid state if the
request times out; accessing any object members may throw an
exception. In Firefox 3.0+ only, script and JSONP requests cannot be
cancelled by a timeout; the script will run even if it arrives after
the timeout period.
对于这种情况,我会使用jquery延迟失败回调。
http://api.jquery.com/deferred.fail/
一个。 您可以维护所有请求的队列。
1 | $.xhrQueue = []; |
湾 将您提出的每个请求排入队列
1 2 3 4 5 | $.ajaxSetup({ beforeSend: function (e, xhr) { $.xhrQueue .push(xhr); } }); |
C。 完成请求与超时的轮询
1 2 3 4 5 6 7 | setInterval(function(){ $.each($.xhrQueue, function (xhr) { //check whether status is complete, //with some try-catch you can know which were the timed-out/not-sent ones }); }, 1000); |
注意:如果不是
试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var setTime = setTimeOut(function() { $.ajax({ url: '<?php bloginfo(' template_directory ');?>/ajax/product.php', type: 'GET', data: { 'product_id': product_id } }).beforeSend(function() { $('#details').html(''); }).done(function(data) { $('.iosSlider').fadeOut('fast'); thisprod.addClass('current'); $('#details').css({ opacity: 0 }).html(data).stop().animate({ left: 0, opacity: 1 }, 800); }); }, 2000); |