我正在尝试使用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请求。
使用JQuery可以轻松完成AJAX请求。您需要做的就是<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...
}
getchat.php
每次浏览器调用时都会加载此功能readChat()
,并设置readChat()
每5秒调用一次的间隔。里面的函数$.get()
是您可以使用从接收的数据的地方getchat.php
。它通常只是一个字符串,您可以将其插入到聊天区域或div中,但这取决于您如何使getchat.php
脚本工作。
最后,您只需创建一个名为的新PHP脚本getchat.php
,它将读取聊天文件并以您希望看到的格式将其回显到页面中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句