这样我就可以测量我的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
});
但是,如果我想获取同一页面多个ajax调用的处理时间,该怎么办?
我的意思是这样的:
var i;
var j = 5;
for (i = 0; i < j; i++) {
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
});
}
我需要知道每个调用的响应时间
最佳答案
你的问题是有 no block scope in JavaScript ,因此 ajaxTime 不会在每次循环迭代中重新声明(它被设置为每次迭代中的当前时间)。您可以将 $.ajax
代码重构为函数或使用闭包,以便为每个请求使用新的 ajaxTime
变量:
var i;
for (i = 0; i < 5; i++) {
makeRequest(i);
}
function makeRequest(i) {
var ajaxTime = new Date().getTime();
$.ajax({
url: 'some.php',
type: 'POST'
}).done(function () {
var total = new Date().getTime() - ajaxTime;
console.log('Elapsed time: ' + total);
});
}
关于javascript - 测量同一页面多个 AJAX 调用的处理时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23569452/