2013-10-24 23 views
0

我知道您可以在$.ajaxSetup上设置jQuery的timeout属性,但会中止当前的超时请求。全球处理jQuery的AJAX超时而无需中止

我有什么选择来监控每个单独的AJAX请求所花费的时间,以便用户等待的反馈目的。

伪代码:

if(timeTaken > 1000){ 
    // taking a long time 
} else if (timeTaken > 5000){ 
    // this is embarrassing, please refresh! 
} 

但随着jQuery的AJAX全球范围内实施......

回答

0

你要看看ajaxStart()和.ajaxStop()方法。

var totalTime = null; 
var cachedTime = null; 

function alertLoadingTime() { 
    if(!totalTime) return; 
    var loadingTime = totalTime/1000; 
    console.log("loaded " + loadingTime + " seconds"); 
} 

function timingStart() { 
    cachedTime = new Date; 
} 

function timingEnd() { 
    var endTime = new Date; 
    totalTime += endTime - cachedTime; 
    cachedTime = null; 
    alertLoadingTime(); 
} 

$(document).ajaxStart(timingStart); 

$(document).ajaxStop(timingEnd); 

然后检查totalTime以提醒smth。

+0

感谢你们,我有类似的东西,但是当你有多个同时发生的请求发生时,这种情况会有所... – benhowdle89

+0

然后你可以使你的ajax调用同步到那个页面jQuery.ajaxSetup({async:false});让你的调用,然后让jQuery.ajaxSetup({async:true});再次 –