开发者

Getting AJAX Request Duration [duplicate]

This question already has answers here: Find out how long an Ajax request took to complete (9 answers) Closed 8 years ago.

I would like to get the duration for a certain ajax request using jquery. For instance I am using this script:

$.ajax({
  type: "GET",
  ur开发者_StackOverflow社区l: "http://localhost/thescript.php",
  success: function(data){
    $("#container").html(data);
  },
  complete: function(jqXHR, textStatus){
    alert("http://localhost/thescript.php took 'n' seconds to load");
  }
});

I would like to be able to know how long this ajax script loaded the url "http://localhost/thescript.php". For instance alert: "http://localhost/thescript.php took 'n' seconds to load".


You can use the beforeSend() and complete() functions to compare the current timestamps and calculate the difference.

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

Here you can see all callback hooks provided by $.ajax: http://api.jquery.com/jQuery.ajax/#callback-functions


How 'bout:

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");
  }
});


something like this:

var start_ts;
$.ajax({
 type: "GET",
 url: "http://localhost/thescript.php",
 beforeSend: function() {
   start_ts = new Date().getTime();
 }
 success: function(data){
  $("#container").html(data);
 },
 complete: function(jqXHR, textStatus){
  var end_ts = new Date().getTime();
  var dif = (end_ts - start_ts) / 1000; /* convert milisec to sec */
  alert("http://localhost/thescript.php took '"+dif+"' seconds to load");
 }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜