I need a help with showing a loading time when user loading a page in a div with ajax with onchange. so this is my code,
So when the page is loading the gif is showing ok but not the time,
<div class="col-xs-3" style="display:none;" id="wait"><img src="../img/loading_dark.gif" alt="" style="width: 900px; height: 32px; position: relative;"/>
<div id="load_time"></div>
</div>
and my ajax code,
var beforeload = (new Date()).getTime();
$('#jobname').on('change', $(this), function () {
var job = $('#jobname').val();
$.ajax({
type: 'POST',
url: "divpages/show_gen_overview_report.php",
data: {job: job},
beforeSend: function ()
{
$("#wait").css("display", "block");
var afterload = (new Date()).getTime();
seconds = (afterload-beforeload) / 1000;
$('#load_time').text('Page load time :: ' + seconds + ' sec(s).');
},
success: function (response, textStatus, jqXHR) {
$("#wait").css("display", "none");
$('#FinalOverviewReportContentDiv').html(response);
}
});
});
what i am trying to do is while the page is loading, the gif is showing alongside the loading time. So, when the page is finished loading user can see how long the page is loading.. thanks in advance
答案 0 :(得分:2)
请考虑以下代码段:
$('#jobname').on('change', $(this), function () {
var job = $('#jobname').val();
var beforeload = new Date();// initialize before sending ajax call not globally
$.ajax({
type: 'POST',
url: "divpages/show_gen_overview_report.php",
data: {job: job},
beforeSend: function ()
{
$("#wait").css("display", "block");
},
success: function (response, textStatus, jqXHR) {
$("#wait").css("display", "none");
var afterload = new Date();
seconds = (afterload-beforeload) / 1000; //calculate in success function not beforesend
$('#load_time').text('Page load time :: ' + seconds + ' sec(s).');
$('#FinalOverviewReportContentDiv').html(response);
}
});
});
答案 1 :(得分:1)
您的逻辑错误,beforesend
变量必须在beforeSend handler
中设置,afterload
应该在success
处理程序中。
如果您不想在所有AJAX请求中发生,您也可以使用AJAX全局事件:
var beforeSend = -1;
$.ajaxSend(function() {
beforeSend = Date.now();
$("#wait").css("display", "block");
});
$.ajaxComplete(function() {
var afterSend = Date.now();
var seconds = (afterSend-beforeSend) / 1000;
$('#load_time').text('Page load time: ' + seconds + ' sec(s).');
});