【发布时间】:2021-06-15 22:14:49
【问题描述】:
在我的 wwwroot 中,我放置了文件 123.txt。我的简单服务将字符串放入此文件。此外,在 index.php 中,我使用 123.txt 的内容作为变量。 123.txt文件更改时如何强制浏览器刷新页面?
【问题讨论】:
在我的 wwwroot 中,我放置了文件 123.txt。我的简单服务将字符串放入此文件。此外,在 index.php 中,我使用 123.txt 的内容作为变量。 123.txt文件更改时如何强制浏览器刷新页面?
【问题讨论】:
您可以在页面加载时在 javascript 中设置该值,然后每 X 秒轮询一次文件以查看它是否已更改。
<script type="text/javascript">
let originalValue = "<?php echo file_get_contents('123.txt'); ?>";
function checkFileForChanges() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
if (xmlhttp.responseText != originalValue) {
window.location.reload();
}
}
else if (xmlhttp.status == 400) {
//alert('There was an error 400');
}
else {
// alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "123.txt", true);
xmlhttp.send();
}
let interval = setInterval(()=> {
checkFileForChanges();
}, (30*1000)) // every 30 seconds
</script>
【讨论】: