发送新消息时更新页面

  • 本文关键字:更新 新消息 php
  • 更新时间 :
  • 英文 :


这是以类似于松弛的方式运作的。我需要页面动态更新,以防用户正在键入。

我有index.phpmessages.htmlnewmessage.php

聊天页面(index.php(如下所示:

<h1>Chat</h1>
<?php
echo file_get_contents("./messages.html") ;
?>
<br>
<form action="newmessage.php" method="post">
<input type="text" placeholder= "Compose a new message..." name="message" required>
<input type="submit"><br>

PHP 在newmessage.php中看起来像这样:

<?php
$message = $_POST["message"];
$timestamp =date('l jS of F Y h:i:s A');
$text = "<hr>{$message} <br> from: {$_SERVER['PHP_AUTH_USER']} at: {$timestamp} <br><br> n";
$file = fopen("./messages.html","a+ n");
fwrite($file, $text);
fclose($file);
?>
<meta http-equiv="refresh" content="0.5;URL='/chat/index.php'"/>
<p>Sending Message...</p>

因此,消息会显示给发送消息的用户,但不会显示聊天中的其他人。如果其他用户正在键入某些内容,并且我尝试仅进行<?php echo file_get_contents("./messages.html") ; ?>刷新或使用 AJAX 或事件侦听器,我无法使用元刷新。我需要在新消息发布到messages.html后动态更新该内容。

任何指示将不胜感激。提前谢谢。

update because answer edit was rejected

function reloadData()
{
var now = new Date();
url = 'liveData?' + now.getTime();
try {
req = new XMLHttpRequest();
} catch (e) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (oc) {
alert("No AJAX Support");
return;
}
}
}
req.onreadystatechange = processReqChange;
req.open("GET", url, true);
req.send(null);
}
function processReqChange()
{
// If req shows "complete"
if (req.readyState == 4)
{
dataDiv = document.getElementById('currentData');
// If "OK"
if (req.status == 200)
{
// Set current data text
dataDiv.innerHTML = req.responseText;
// Start new timer (1 min)
timeoutID = setTimeout('reloadData()', 60000);
}
else
{
// Flag error
dataDiv.innerHTML = '<p>There was a problem retrieving data: ' + req.statusText + '</p>';
}
}
}

获取您正在寻找的动态更新的最佳方法是 AJAX,因为您并不真正想要一直进行真正的刷新。你说,你试过AJAX?这种方法是怎样的?

我的提示是要对Web架构有一个基本的了解。尝试了解您找到的JS代码以及AJAX的工作原理。你以前使用过JS吗?如果没有,请学习基础知识。

将 url 变量更改为您在服务器上用于返回数据的 url。是的,您将需要它。然后查看回调函数(processReqChange(((。

我给你的不仅仅是提示,但在你的早期阶段,最好独自做很多事情,并由更有经验的开发人员提供一些提示。

最新更新