我正在尝试为我的网站制作一个 PHP/JavaScript 聊天系统。如何在不刷新页面的情况下做到这一点?
JavaScript 可以: --动态添加文本到文本框。
PHP 可以: --将聊天内容保存到聊天日志文件,并更新聊天室以便每个人都可以看到。
第二部分似乎需要您刷新页面。我不想每次用户说了什么就刷新页面。 有没有一种方法可以在后台运行 PHP,而不需要执行 POST 或 GET?我是否需要使用不同的服务器端语言,例如 Python 或 Ruby?任何帮助将不胜感激。
最佳答案
如果你想创建一个只使用一个日志文件的聊天室应用程序,即你网站上的每个人都登录到同一个房间,那么使用 php 和 ajax 以及一些 jquery 并不难。流程如下:您希望用户输入消息并发送,对吗?您需要一个表单:
<form name="message" action="">
<input name="usermsg" type="text" id="usermsg" size="63" />
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />
</form>
这是表单的标记,接下来,您需要一些能够无缝接收用户输入的内容,无论用户在文本框中输入什么内容并将其发送到脚本,这就是 ajax 的用武之地:
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript" >
//when the user clicks the button with the id submitmsg, the input is taken
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
//after the input's value is taken, it's sent to a script called
//pst.php
$.post("post.php", {text: clientmsg});
//after the message is sent, the input's value is set to null
//to allow the user to type a new message
$("#usermsg").attr("value", "");
return false;
});
</script>
完成此操作后,我们需要查看脚本 post.php 的外观以及它的作用,基本上,它获取通过 ajax 发送给它的输入并将其写入文件中,然后将该文件加载到网页上然后可以查看用户之间发送的所有消息,进一步使用 ajax 在一定时间后重新加载文件,以便用户始终了解其包含的任何消息,这是 php 脚本:
<?
session_start();
if(isset($_SESSION['name'])){
$text = $_POST['text'];
$fp = fopen("log.html", 'a');
fwrite($fp, "<div class='msgln'><b>".$_SESSION['name']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
请注意,我使用了一个 session ,这是为了获取登录用户的名称并将其输出到日志文件中。无论如何,我相信您可以看到登录系统如何适应这个情况,将数据写入文件后,我们需要上传它以便用户可以看到:
<div id="chatbox">
<?php
if(file_exists("log.html") && filesize("log.html") > 0){
$handle = fopen("log.html", "r");
$contents = fread($handle, filesize("log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
这就是日志文件将被加载的分区,现在,只剩下一件事了,我们需要在一定时间后重新加载文件,并且可能添加自动滚动功能:
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#inner").attr("scrollHeight") - 20;
$.ajax({
url: "log.html",
cache: false,
success: function(html){
$("#inner").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#inner").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#inner").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2500); //Reload file every 2.5 seconds
就这样,应该可以了,希望这对您有帮助,以防您还没有得到有用的答案,否则您可能已经等了很长时间了。
关于php - 制作 PHP JavaScript 聊天室,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12612867/