Javascript获取文件内容循环

Javascript get file contents loop

本文关键字:循环 文件 获取 Javascript      更新时间:2023-12-09

我一直在尝试让一个函数每秒重新加载一次。

我可以用php获取文件内容(和元页面重载)来实现这一点,但我也使用JS来显示时间,它在加载时不是即时的,所以它有闪烁的效果。

我已经用JS尝试过了,但它什么都没有显示。

    <!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Vivarium Enviroment Control Centre</title>
<link rel="stylesheet" href="style.css">
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
    function updateTime() {
        var currentTime = new Date();
        var hours = currentTime.getHours();
        var minutes = currentTime.getMinutes();
        var seconds = currentTime.getSeconds();
        if (minutes < 10){
            minutes = "0" + minutes;
        }
        if (seconds < 10){
            seconds = "0" + seconds;
        }
        var v = hours + ":" + minutes + ":" + seconds + " ";
        if(hours > 11){
            v+="PM";
        } else {
            v+="AM"
        }
        setTimeout("updateTime()",1000);
        document.getElementById('time').innerHTML=v;
    }
updateTime();
$("document").ready(function(){
    setInterval(function(){
        $("#wifi").load('wifiout.php');
    },1000);
});

function changeStatus() {
    var image = document.getElementById('lightStatus');
    if (image.src.match("lightoff")) {
        image.src = "lighton.png";
    } else {
        image.src = "lightoff.png";
    }
}
</script>
</head>
<body>
<div id="topbar">
    <span id="time"></span>
    <div id="wifi"></div>
    <img id="lightStatus" class="right" onclick="changeStatus()" src="lightoff.png" width="32" height="32">
</div>
</body>
</html>

工作小提琴

您缺少jQuery插件声明,请在脚本标记前添加以下行:

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>

注意:在ready函数中调用updateTime()函数,否则会出现以下错误:

TypeError:无法设置空的属性"innerHTML"

因为您正在尝试在页面尚未完全加载时使用span time

希望这会有所帮助。