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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12763987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:00:36  来源:igfitidea点击:

How do I get the response time from a jQuery ajax call?

jqueryajaxtimerequestresponse

提问by Dumpen

So I am working on tool that can show long a request to a page is taking.

所以我正在开发可以显示对页面的请求很长时间的工具。

I am doing this by using jQuery Ajax (http://api.jquery.com/jQuery.ajax/) and I want to figure out the best way to get the response time.

我通过使用 jQuery Ajax (http://api.jquery.com/jQuery.ajax/) 来做到这一点,我想找出获得响应时间的最佳方法。

I found a thread (http://forum.jquery.com/topic/jquery-get-time-of-ajax-post) which describes using the "Date" in JavaScript, but is this method really reliable?

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

An example of my code could be this below

我的代码示例如下

$.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
});

回答by FIG-GHD742

The most simple method would be to add var ajaxTime= new Date().getTime();before the Ajax call and in the doneget the current time to calculate how long the Ajax call took to make.

最简单的方法是var ajaxTime= new Date().getTime();在 Ajax 调用之前添加并在doneget 当前时间中计算 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
});

Or in case of you want to know how long time this take on the server side. Do the same and print the time in the return value from some.php.

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