用一个PHP脚本同时刷新两个DIV&;jQuery加载


Refreshing two DIVs at the same time with one PHP script & jQuery load

我想做的是:1)显示一个div中最后一次备份的实时计数2) 随着时间的推移,更改另一个DIV的颜色以及其中的文本

我尝试的方法:通过使用Jquery加载刷新元素。

到目前为止的成功:我已经成功地显示了时间计数,但无法理解如何更改其他DIV.的文本和颜色

我在想,如果有可能在每次加载中传递脚本的颜色值,那么它可能会起作用,但不确定我的方法和我对任务的想法是否正确。我浏览了所有的网页,但都没有派上用场。

我真的很感激你的帮助。也欢迎对代码进行改进。:)

提前感谢。。

PHP

<?php
$dir="DB_Backups/";
$file= array();
$file = scandir($dir, 1);
if ('.' === $file || '..' === $file)
    continue;
$newest_file=$dir.$file[0];
if(is_file($newest_file)){
$time=time()-filemtime($newest_file);
if($time<2){
    echo "Last Backup just now";
}
if($time>=2 && $time<60){
    echo "Last Backup few seconds ago";
}
else
if($time>=60 && $time<2*60){
echo "Last Backup a minute ago";
}
else
if($time>=2*60 && $time<3600){
    echo "Last Backup few minutes ago";
}
else
if($time>=3600 && $time<2*3600){
    echo "Last Backup an hour ago";
}
else
if($time>=2*3600 && $time<86400){
    echo "Last Backup few hours ago";
}
else
if($time>86400){
    echo "Last Backup on ".date("F d, Y",filemtime($newest_file));
}
}
else{
    echo "Backup not yet performed!";
}
?>

JQuery

<script src="jquery-1.9.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
    setInterval(function(){
        $("#status").load("f_backupstatus.php");
    },1000);
});
</script>

HTML

<div id="test" style="background-color: #0066CC;">
<span id="status" style="color:#FFFFFF;"></span></div>
<div id="colour" style="background-color: #999999">colour</div>

您可以始终返回一个JSON对象。在PHP文件中,最好有一个包含响应和颜色的数组:

PHP:

<?php
$dir = "DB_Backups/";
$file = array();
$file = scandir($dir, 1);
$newest_file = $dir.$file[0];
$responses = array(
    ['status' => 'Last Backup just now', 'colour' => 'green'],
    ['status' => 'Last Backup a few seconds ago', 'colour' => 'blue'],
    ['status' => 'Last Backup a minute ago', 'colour' => 'violet'],
    ['status' => 'Last Backup a few minutes ago', 'colour' => 'yellow'],
    ['status' => 'Last Backup on'.date("F d, Y", filemtime($newest_file)), 'colour' => 'orange'],
    ['status' => 'Backup not performed yet!', 'colour' => 'red'],
);
if(is_file($newest_file)) {
    $time=time()-filemtime($newest_file);
}
if ($time > 86400) {
    $return = $responses[5];
} else if ($time > 7200) {
    $return = $responses[4];
} else if ($time > 3600) {
    $return = $responses[3];
} else if ($time > 120) {
    $return = $responses[2];
} else if ($time > 60) {
    $return = $responses[1];
} else {
    $return = $responses[0];
}
return json_encode($return);
?>


Javascript:

$(function() {
    setInverval(function() {
        $.ajax({
            url: 'f_backupstatus.php',
            success: function(data) {
                data = JSON.parse(data);
                $('#status').text(data['status']);
                $('#colour').css('background-color', data['colour'])
            }
        });
    }, 1000);
}):