如何在不刷新 php 的情况下打开、读取、关闭、更新、重新打开和读取文件



我正在尝试使用 html 和 php 制作聊天应用程序。

我正在编写一个包含整个聊天的.txt文件,并希望每五秒阅读一次而不刷新我的页面。我尝试在javascript中使用循环,但是再次打开文件后它不会刷新文件。

function readChat(){
clearArea();
<?php
if ($file = fopen("chat.txt", "r")) {
while(!feof($file)) {
$line = trim(fgets($file));
if($line !== " "){
$arr = explode(":", $line, 2);
$name = $arr[0];
$string = $arr[1];
$string = str_replace(array("r", "n"), '', $string);

if($name === $_COOKIE["username"] && $string !== "" && $string !== " " && $string !== "n"){
echo "selfMessage("".$string."");";
}else if($line !== "" && $line !== " " && $line !== "n" && $string !== "" && $string !== " " && $string !== "n"){
echo "otherMessage("".$string."", "".$name."");";
}
}
}
fclose($file);
}

?>
}
window.setInterval(function() {
readChat();
}, 5000);

这就是我到目前为止尝试过的。

您遇到的问题是由于混合了PHP和Javascript代码。

首先,您应该知道PHP代码在服务器上执行,该服务器生成将发送到客户端(Web浏览器)的页面内容。然后,该Web浏览器执行它收到的页面内容中包含的Javascript代码。

您已经看到聊天为什么没有更新吗?

当请求页面时,您的 PHP 函数仅执行一次,并将聊天消息插入readChat()函数的正文中。当浏览器收到包含readChat()的网页数据时,它只会看到聊天消息,就好像它们被硬编码到函数中一样!

例如,以下 PHP 脚本:

function someJSFunc() {
<?php
$now = date('m/d/Y H:i:s', time());
echo "var now = '$now';";
?>
console.log(now);
}

导致将以下函数发送到客户端:

function someJSFunc() {
var now = '6/4/2019 16:39:18';
console.log(now);
}

无论客户端调用someJSFunc()多少次,它都将始终输出相同的日期和时间,因为那是PHP函数执行的时间。

有时以这种方式混合PHP和Javascript可能非常有用,但是要完成您正在寻找的内容,您将需要使用AJAX请求。

AJAX 请求可以使用 JQuery 轻松完成。您需要做的就是在页眉中添加另一个<script>标记以包含 JQuery 脚本。有关设置 JQuery 的进一步说明可以在他们的网站上找到。

接下来,您必须修复readChat()功能。无需在该函数中使用 PHP,只需使用 javascript 并使用 JQuery 来执行 GET 请求。

function readChat() {
clearArea();
$.get("getchat.php", function(data) {
// inside this function data will contain whatever your PHP script echos
$('#chat').html(data);    // for example, replacing a div with id="chat" with the data received from getchat.php
});
window.setInterval(function() { readChat(); }, 5000);  // I would personally move this outside of readChat() so that it is only called once...
}

此函数将在浏览器每次调用readChat()时加载getchat.php,并设置每 5 秒调用一次readChat()的间隔。$.get()中的功能是您可以使用从getchat.php接收的数据的地方。它通常只是一个字符串,您可以将其插入到聊天区域或div 中,但这取决于您如何使getchat.php脚本工作。

最后,您只需制作一个名为getchat.php的新PHP脚本,该脚本将读取聊天文件并以您希望添加到页面的格式对其进行回显。

最新更新