如果不知道脚本的作用,就无法提前知道运行需要多长时间。即使我们确实知道它的作用,也无法知道它运行的确切时间。如果这都在同一个会话中,您可以在脚本中的某些要点放置“% 完成标记”。我在几个地方这样做。它是一个很好的进度条,我还显示了总运行时间。如果您想要这样的内容,请继续阅读...
(这是使用 jQuery UI progress bar)
如果您的脚本是一个循环,并且每次迭代基本上都在做同样的事情,那么进度条的增长将会非常流畅。如果不是这种情况,并且你的脚本做很多事情非常快,然后一些事情非常慢,那么你的进度条就会像几乎所有 Windows 进度条一样 :) 它可以很快到达某个点然后挂在那里一会儿。
不是在我的电脑上,所以我确定下面有错别字,但你应该能够明白这一点。希望这会有所帮助...
这样的东西会出现在你长时间运行的脚本中......
$_SESSION["time_start"] = microtime(true);
$_SESSION["percentComplete"] = 0;
... some of your php script ...
$_SESSION["percentComplete"] = 10;
... some of your php script ...
$_SESSION["percentComplete"] = 20;
... some of your php script ...
$_SESSION["percentComplete"] = 30;
... etc ...
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script
但如果你的长时间运行的脚本是一个循环,它会更像这样......
$loopCnt = 0;
//your php loop
{
$loopCnt = $loopCnt+1;
//...the meat of your script...
$_SESSION["percentComplete"] = round(($loopCnt/$totalRecordCount)*100);
}
$_SESSION["percentComplete"] = 100;
die();
?> //end of your php script
然后在页面上,用户与 ajax ping 交互可以设置为每隔几秒左右检查一次$_SESSION["percentComplete"] 的值,并根据结果使进度条增长。比如……
function checkScriptProgress()
{
$.ajax({
url: "checkScriptProgress.php",
type: 'get',
cache: false,
success: function( data, textStatus, jqXHR) {
//(1) MOVE THE PROGRESS BAR
//if you are using a jQuery UI progress bar then you could do something like...
//jQuery("#yourProgressBar").progressbar( "option", "value", data.progress );
//if you are using HTML5 progress bars it would look like...
//var pBar = document.getElementById("yourProgressBar");
//pBar.value = data.progress;
//(2) UPDATE ELAPSED TIME
//if you want to display the total run time back to the user then use: data.totalRunTime
//(3) If report is not finished then ping to check status again
if (data.progress < 100) setTimeout("checkScriptProgress();", 1000); //check progress every 1 second so the progress bar movement is fluid
})
});
}
那么checkScriptProgress.php 文件看起来像...
<?php
header('Content-Type: application/json');
$time_end = microtime(true);
$time = $time_end - $_SESSION["time_start"];
echo '{"progress":'.$_SESSION["percentComplete"].',"totalRunTime":'.$time.'}';
die();
?>