如何从jQueryAjax调用中获得响应时间?

如何从jQueryAjax调用中获得响应时间?,jquery,ajax,time,request,response,Jquery,Ajax,Time,Request,Response,所以我正在开发一个工具,它可以显示对页面的长时间请求 我使用jqueryajax来实现这一点(http://api.jquery.com/jQuery.ajax/)我想找出获得响应时间的最佳方法 我找到一根线(http://forum.jquery.com/topic/jquery-get-time-of-ajax-post)它描述了在JavaScript中使用“日期”,但是这个方法真的可靠吗 下面是我的代码示例 $.ajax({ type: "POST", url: "some

所以我正在开发一个工具,它可以显示对页面的长时间请求

我使用jqueryajax来实现这一点(http://api.jquery.com/jQuery.ajax/)我想找出获得响应时间的最佳方法

我找到一根线(http://forum.jquery.com/topic/jquery-get-time-of-ajax-post)它描述了在JavaScript中使用“日期”,但是这个方法真的可靠吗

下面是我的代码示例

$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    // Here I want to get the how long it took to load some.php and use it further
});

最简单的方法是添加
var ajaxTime=new Date().getTime()
在Ajax调用之前和
done
中获取当前时间,以计算进行Ajax调用所需的时间

var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
    // Here I want to get the how long it took to load some.php and use it further
});
或者,如果您想知道这在服务器端需要多长时间。
做同样的事情,并在some.php的返回值中打印时间。

看看这个答案:为什么我们不能在dev tool goto networks->XHR中使用chrome开发工具呢?你可以看到所有请求的大小和时间,你可以使用
Date.now()
而不是更长的
new Date().getTime()
。它不仅保存字符,还保存创建
Date
对象的过程。@DanielBöhmer关于
Date.now()
-它在一些旧浏览器(如IE8)中不可用,您可能需要一个polyfill,请参阅downvoting-不适用于多个请求