Getting AJAX Request Duration [duplicate]
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");
}
});
精彩评论