如何从 jQuery ajax 调用中获取响应时间? [英] How do I get the response time from a jQuery ajax call?

查看:32
本文介绍了如何从 jQuery ajax 调用中获取响应时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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.

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

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?

我的代码示例如下

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

推荐答案

最简单的方法是在 Ajax 调用之前添加 var ajaxTime= new Date().getTime();done 获取当前时间以计算 Ajax 调用花费的时间.

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

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

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.

这篇关于如何从 jQuery ajax 调用中获取响应时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆