如何从jQuery ajax调用获得响应时间?

所以我正在研究可以显示页面请求的工具。

我通过使用jQuery Ajax(http://api.jquery.com/jQuery.ajax/)来做这件事,我想弄清楚获得响应时间的最佳方法。

我发现了一个线程(http://forum.jquery.com/topic/jquery-get-time-of-ajax-post),它描述了在JavaScript中使用“Date”,但这种方法真的可靠吗?

我的代码示例如下

$.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的返回值中打印时间。