【问题标题】:How do I get the response time from a jQuery ajax call? [duplicate]如何从 jQuery ajax 调用中获取响应时间? [复制]
【发布时间】:2012-09-27 15:45:42
【问题描述】:

所以我正在开发一种工具,可以显示对页面的请求所花费的时间。

我通过使用 jQuery Ajax (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
});

【问题讨论】:

  • 看到这个答案:stackoverflow.com/a/3700307/889678
  • 为什么我们不能在开发工具 goto 网络中使用 chrome 开发工具 -> XHR 你可以看到所有请求的大小和时间

标签: jquery ajax time request response


【解决方案1】:

最简单的方法是在 Ajax 调用之前添加 var ajaxTime= new Date().getTime(); 并在 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 的返回值中打印时间。

【讨论】:

  • 您可以使用Date.now() 而不是更长的new Date().getTime()。它不仅可以保存字符,还可以保存 Date 对象的创建。
  • @DanielBöhmer 关于Date.now() - 它在一些较旧的浏览器(例如IE8)中不可用,您可能需要一个polyfill,请参阅MDN
  • downvoting - 不适用于多个请求
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多