获取AJAX请求持续时间

我想使用jquery获取某个ajax请求的持续时间。 例如,我正在使用此脚本:

$.ajax({ type: "GET", url: "http://localhost/thescript.php", success: function(data){ $("#container").html(data); }, complete: function(jqXHR, textStatus){ alert("http://localhost/thescript.php took 'n' seconds to load"); } }); 

我希望能够知道这个ajax脚本加载了URL“http://localhost/thescript.php”多长时间。 例如警告:“http://localhost/thescript.php加载’n’秒”。

您可以使用beforeSend()complete()函数来比较当前时间戳并计算差异。

http://api.jquery.com/jQuery.ajax/

在这里,您可以看到$.ajax提供的所有回调挂钩: http : //api.jquery.com/jQuery.ajax/#callback-functions

怎么样:

 var start = new Date().getTime(); $.ajax({ type: "GET", url: "http://localhost/thescript.php", success: function(data){ $("#container").html(data); }, complete: function(jqXHR, textStatus){ var duration = (new Date().getTime() - start) / 1000; alert("http://localhost/thescript.php took '" + duration + "' second(s) to load"); } }); 

像这样的东西:

 var start_ts; $.ajax({ type: "GET", url: "http://localhost/thescript.php", beforeSend: function() { start_ts = new Date().getTime(); } success: function(data){ $("#container").html(data); }, complete: function(jqXHR, textStatus){ var end_ts = new Date().getTime(); var dif = (end_ts - start_ts) / 1000; /* convert milisec to sec */ alert("http://localhost/thescript.php took '"+dif+"' seconds to load"); } });