gpt4 book ai didi

javascript - php:在文件更改时重新加载 div

转载 作者:行者123 更新时间:2023-11-28 01:17:38 24 4
gpt4 key购买 nike

我有一个 Raspberry Pi,上面连接了一些按钮,可以更改某个文件中包含的值,例如“setting.txt”。例如,它的内容可能很简单

42

就是这样。这些按钮会触发更改此文件内容的过程(例如,42 变为 43)。

需要在Apache2运行的网站上显示该值,所以我构建如下:

<html>    
<body>
<div id="fileContent"></div>
</body>

<script type="text/javascript">

window.onload = function() {
var $interval = 100;
setInterval(updateDivByPHP, $interval, "fileContent", "getcontent.php");
}

function updateDivByPHP($id, $phpFile) {
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
document.getElementById($id).innerHTML = xmlhttp.responseText;
}

xmlhttp.open("POST", $phpFile);
xmlhttp.send();
}

</script>
</html>

其中 getcontent.php 就像

一样简单
<?php
include "setting.txt";
?>

将刷新间隔设置为 100 毫秒后,我预计文件更改后的刷新延迟会相当短,但内容更新最多需要 2 秒。

对于我想要的东西,是否有修复或更有效/规范的方法?

编辑

如果可以完全跳过该文件并以某种方式将其输出直接通过管道传输到网站,那就更好了......

最佳答案

不要使用include,使用readfile或者file_get_contentsinclude有一些缓存机制(Can'找不到关于它的信息,但请查看我下面的示例)并且速度较慢,因为它必须评估文件。

<?php
readfile("setting.txt");
//echo file_get_contents("setting.txt");
?>

我在 apache 中使用 include 做了一些测试:

<?php
include("test.txt"); //outputs "hi"

//override "test.txt"
file_put_contents("test.txt", "bye");

readfile("test.txt"); //outputs "bye"
include("test.txt"); //outputs "hi"
?>

如果你想在文件被修改后立即发送到浏览器中,你应该使用 websockets 和文件观察器。 (您可以使用 node.js 来完成它,使用:fs.watchsocket.io )

node.js 的一些文件观察器模块

关于javascript - php:在文件更改时重新加载 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35116427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com