获取AJAX请求持续时间

Chr*_*oel 1 javascript ajax jquery

我想使用jquery获取某个ajax请求的持续时间.例如,我正在使用此脚本:

$.ajax({
  type: "GET",
  url: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    alert("http://localhost/thescript.php took 'n' seconds to load");
  }
});
Run Code Online (Sandbox Code Playgroud)

我希望能够知道这个ajax脚本加载了URL"http://localhost/thescript.php"多长时间.例如警告:"http://localhost/thescript.php加载'n'秒".

Dan*_*gen 5

您可以使用beforeSend()complete()函数来比较当前时间戳并计算差异.

http://api.jquery.com/jQuery.ajax/

在这里,您可以看到所有回调挂钩$.ajax:http: //api.jquery.com/jQuery.ajax/#callback-functions


T.J*_*der 5

怎么样:

var start = new Date().getTime();
$.ajax({
  type: "GET",
  url: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    var duration = (new Date().getTime() - start) / 1000;
    alert("http://localhost/thescript.php took '" + duration + "' second(s) to load");
  }
});
Run Code Online (Sandbox Code Playgroud)