2012-07-20 73 views
4
var refreshId_hxlatestposts = setInterval(function() { 
var el = $("#hxlatestposts"); 
var req = $.get("example.php"); 
el.fadeOut('slow', function() { 
    req.done(function(data){ 
     el.html(data).fadeIn('slow'); 
    }); 
}); 
}, 60000); 

这就是我用来刷新div的每一分钟,有时它会挂起,当它从网站获取饲料是down或什么的。我想要一些如何有超时,所以如果它不能在X秒内加载PHP文件,然后返回'加载失败'。添加一个超时加载()

回答

2

jQuery文档(.ajaxSetup())建议使用.ajaxSetup()将值f或timeout,而不是在个别请求中使用它。

如果请求失败,您可以使用request.fail()注册一个函数。

$.ajaxSetup({ 
    timeout: 5000 
}); 

var refreshId_hxlatestposts = setInterval(function() { 
    var el = $("#hxlatestposts"); 
    var req = $.get("example.php"); 
    el.fadeOut('slow', function() { 
     req.done(function(data) { 
      el.html(data).fadeIn('slow'); 
     }); 
     req.fail(function(jqXHR, textStatus) { 
      el.html('Fail to load').fadeIn('slow'); 
     }); 
    }); 
}, 60000); 
+0

如果我是使用此代码剪断的X,我会只需要在JS文件的顶部放置一次ajaxSetup?没关系,我想我应该阅读文档。 使用任何函数的所有后续Ajax调用将使用新的设置,除非被单个调用覆盖,直到下一次调用$ .ajaxSetup()。 – Keelan 2012-07-20 20:33:35

2

不错的使用延缓对象。

如果用$.ajax代替$.get,则可以添加超时。

var req = $.ajax({ 
    url: "example.php", 
    type: "GET", 
    timeout: 5000 // 5 seconds 
}); 

,然后添加故障处理程序

req.done(function(){...}).fail(function(){ 
    alert("failed to load"); 
}); 
1

你要检查传入响应的状态,以确保服务返回的200个OK状态。这比仅仅等待超时更可靠 - 你会知道它是否是好数据,或者可以通过将超时放入完整函数来决定重试。

$.ajax({ 
    //...   
    success: function(data, textStatus, xhr) { 
     console.log(xhr.status); 
     //handle status codes etc. 
     // then set your timeout 

    }, 
    complete: function(xhr, textStatus) { 
     console.log(xhr.status); 
     //handle status codes etc. 
     // then set your timeout 

    }, 

    // OR 

    fail: function(xhr, textStatus){ 
     //retry code or timeout 
    } 

    }); 
1

jQuery的$不用彷徨,不过是为了$就简写,这是当需要更大的灵活性,使用(你的情况,是)

替换$.get("example.php");有: $.ajax({ type: "GET", url: "example.php", timeout: X*1000, }).done(function(data) { el.fadeOut('slow', function() { el.html(data).fadeIn('slow'); }); }, 60000); });

哪里X是您希望它等待的秒数(超时)

+0

Sry基因,我做了一些修改为新密码,这样你就可以取代下面的'变种EL = $(“#hxlatestposts”)的代码;' – 2012-07-20 18:30:11