php - 发送新消息时更新页面
问题描述
这是以与 slack 类似的方式运行的。我需要页面动态更新,以防用户输入。
我有index.php
,messages.html
并且newmessage.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())。
我会给你的不仅仅是提示,但在你的早期阶段,最好单独做很多事情,并由更有经验的开发人员提供一些提示。
推荐阅读
- javascript - workbox默认检测无网络或离线并刷新页面?
- vuejs2 - vue-infinite-loading 未检测到结束并进行加载
- javascript - 我不知道如何在 nodejs express 服务器中存储来自 api 调用的 json 数据,并将其发送到 react 本机客户端
- python-3.x - 尝试从 TMDB 获取系列背景
- elasticsearch - Magento\Elasticsearch7\Model\Client\Elasticsearch::query() 的返回值必须是数组类型,Model/Elasticsearch.php:367 中返回的字符串
- reactjs - web3-shh 包将在 1.3.5 版本中被弃用,不再受支持
- github-actions - 减少 GitHub Actions 步骤中的样板文件
- node.js - 无法在 Ubuntu 19.04 中安装 Node.js
- python - Python pytype 安装:无法为 pytype 构建轮子,无法为使用 PEP 517 的 pytype 构建轮子
- visual-studio - 为什么我的VS2008窗口经常刷新甚至卡死?