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

Dum*_*pen 17 ajax time jquery response request

所以我正在开发一种工具,可以显示对页面的请求.

我是通过使用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
});
Run Code Online (Sandbox Code Playgroud)

FIG*_*742 37

最简单的方法是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
});
Run Code Online (Sandbox Code Playgroud)

或者如果您想知道服务器端需要多长时间.执行相同操作并在some.php的返回值中打印时间.

  • 您可以使用`Date.now()`而不是更长的`new Date().getTime()`.它不仅可以保存字符,还可以节省"Date"对象的创建. (12认同)
  • @DanielBöhmer关于`Date.now()`-在某些较旧的浏览器(例如IE8)中不可用,您可能需要一个polyfill,请参阅[MDN](https://developer.mozilla.org/en/docs/Web/ JavaScript /参考/ Global_Objects /日期/现在) (2认同)