在JavaScript函数中重新执行PHP脚本
我编写了一段代码,以便在每次修改文件时(在服务器上)重新读取该文件的内容。场景如下:在JavaScript函数中重新执行PHP脚本,javascript,php,Javascript,Php,我编写了一段代码,以便在每次修改文件时(在服务器上)重新读取该文件的内容。场景如下: - The webpage is loaded - If the file (on the server) is newer than the starting time of the page (the time when the webpage was started), the content of the file is read - If the file is modified later, the
- The webpage is loaded
- If the file (on the server) is newer than the starting time of the page (the time when the webpage was started), the content of the file is read
- If the file is modified later, the content must be read again by PHP script
我尝试了使用EventSource。以下是浏览器的代码:
<html>
<head>
<?php
$startTime = time();
$flag = 0;
?>
<script type="text/javascript" language="javascript">
lastFileTime = <?php echo $startTime; ?>;
var fileTime;
if(typeof(EventSource) !== "undefined") {
var source=new EventSource("getFileTime.php");
source.onmessage = function(event) {
fileTime = parseInt(event.data);
if (fileTime > lastFileTime) {
readFile();
lastFileTime = fileTime;
}
};
}
else {
alert("Sorry, your browser does not support server-sent events.");
}
function readFile() {
<?php
$fid = fopen("file.bin", "rb");
... // Read the content of the file
$flag = $flag + 1;
?>
... // Transfer the content of the file to JavaScript variables
flag = <?php echo $flag; ?>;
}
</script>
</head>
<body>
...
</body>
</html>
当我启动网页并随后创建
file.bin
时,第一次调用了readFile()
(我检查了值flag=1
。但是,如果我再次修改file.bin
,显然readFile()
未被调用。我检查了文件的内容;它仍然来自上一个文件,而且标志仍然是1。JavaScript函数中的PHP脚本似乎只能调用一次。如何在JavaScript函数中重新执行PHP脚本?您的PHP脚本需要保持活动状态,向客户端发送新事件恩,有些事情发生了变化:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastFiletime = null;
while (true) {
$filetime = filemtime("file.bin");
if ($filetime != $lastFiletime) {
echo "data: {$filetime}\n\n";
$lastFiletime = $filetime;
flush();
}
}
我需要的是在readFile()中重新执行PHP脚本
每次修改file.bin
。我对getFileTime.php
中的脚本没有问题;它工作得很好。无论如何,谢谢你的评论,你的评论让我知道了如何用另一种方法来做这件事。不是这样做的,你不能那样做。必须有一些东西保持活动状态以监视文件的更改,以及something也可以是PHP,因为向客户端发送事件的是PHP。当文件更改时,您无法完全重新执行PHP脚本;这是向后的。您只能从正在运行的程序中监视文件的更改。
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$lastFiletime = null;
while (true) {
$filetime = filemtime("file.bin");
if ($filetime != $lastFiletime) {
echo "data: {$filetime}\n\n";
$lastFiletime = $filetime;
flush();
}
}