首页 > 解决方案 > 发送新消息时更新页面

问题描述

这是以与 slack 类似的方式运行的。我需要页面动态更新,以防用户输入。

我有index.phpmessages.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>';
      }
   }
}

标签: php

解决方案


获得您正在寻找的动态更新的最佳方式是 AJAX,因为您并不总是想要真正的刷新。你说,你试过AJAX?这种方法看起来如何?

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

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

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


推荐阅读