简介聊天应用在互联网上非常普遍。开发人员在构建这些类型的应用程序时也有很多选择。本文介绍如何实现一个基于PHP-AJAX的聊天应用程序,并在不刷新页面的情况下发送和接收消息。核心逻辑在定义应用程序的核心功能之前,让我们先看一下聊天应用程序的基本外观,如下图所示:聊天文本是通过聊天窗口底部的输入框输入的。单击发送按钮开始执行函数set_chat_msg。这是一个基于Ajax的功能,因此无需刷新页面即可将聊天文本发送到服务器。该程序在服务器中执行chat_send_ajax.php以及用户名和聊天文本。////SetChatMessage//functionset_chat_msg(){if(typeofXMLHttpRequest!="undefined"){oxmlHttpSend=newXMLHttpRequest();}elseif(window.ActiveXObject){oxmlHttpSend=newActiveXObject("Microsoft.XMLHttp");}if(oxmlHttpSend==null){alert("BrowserdoesnotsupportXMLHttpRequest");return;}varurl="chat_send_ajax.php";varstrname="noname";varstrmsg="";if(document.getElementById("txtname")!=null){strname=document.getElementById("txtname").value;document.getElementById("txtname").readOnly=true;}if(document.getElementById("txtmsg")!=null){strmsg=document.getElementById("txtmsg").value;document.getElementById("txtmsg").value="";}url+="?name="+strname+"&msg="+strmsg;oxmlHttpSend.open("GET",url,true);oxmlHttpSend。send(null);}PHP模块从QueryString(查询字符串)接收表单数据并将其更新到名为chat的数据库表中。聊天数据库表包含名为ID、USERNAME、CHATDATE和MSG的列。ID字段是一个自动递增字段,因此分配给该ID字段将自动递增。当前日期和时间将更新到CHATDATE列。require_once('dbconnect.php');db_connect();$msg=$_GET["msg"];$dt=date("Y-m-dH:i:s");$user=$_GET["name"];$sql="INSERTINTOChat(USERNAME,CHATDATE,MSG)"."values(".quote($user).",".quote($dt).",".quote($msg).");";echo$sql;$result=mysql_query($sql);if(!$result){thrownewException('Queryfailed:'.mysql_error());exit();}接收数据库表中所有用户的聊天消息,定时器函数设置为以5秒为周期调用以下JavaScript命令,即每5秒执行一次get_chat_msg函数。vart=setInterval(function(){get_chat_msg()},5000);get_chat_msg是一个基于Ajax的函数。它执行chat_recv_ajax.php程序从数据库表中获取聊天信息。在onreadystatechange属性中,连接了另一个JavaScript函数get_chat_msg_result。在从数据库表返回聊天消息时,程序控制传递给get_chat_msg_result函数。////GeneralAjaxCall//varoxmlHttp;varoxmlHttpSend;functionget_chat_msg(){if(typeofXMLHttpRequest!="undefined"){oxmlHttp=newXMLHttpRequest();}elseif(window.ActiveXObject){oxmlHttp=newMicrosoft.XMLHttp");}if(oxmlHttp==null){alert("BrowserdoesnotsupportXMLHttpRequest");return;}oxmlHttp.onreadystatechange=get_chat_msg_result;oxmlHttp.open("GET","chat_recv_ajax.php",true);oxmlHttp.send(null);}在chat_recv_ajax.php程序,通过SQLselect命令收集用户的聊天信息,为了限制行数,在SQL查询中也给出了一个limit子句(limit200),即要求***200行在聊天数据库表,获取到的消息返回给Ajax函数,用于在聊天窗口显示内容。require_once('dbconnect.php');db_connect();$sql="SELECT*,date_format(chatdate,'%d-%m-%Y%r')ascdtfromchatorderbyIDdesclimit200";$sql="SELECT*FROM(".$sql.")aschorderbyID";$result=mysql_query($sql)ordie('Queryfailed:'.mysql_error());//UpdateRowInformation$msg="";while($line=mysql_fetch_array($result,MYSQL_ASSOC)){$msg=$msg."".""."";}$msg=$msg." ";echo$msg;当数据准备好后,JavaScript函数将收集从PHP接收到的数据。这些数据将排列在DIV标签内。oxmlHttp.responseText会保留从PHP程序接收到的聊天消息,并将其复制到DIV标签的document.getElementById(“DIV_CHAT”).innerHTML属性中。functionget_chat_msg_result(t){if(oxmlHttp.readyState==4||oxmlHttp.readyState=="complete"){if(document.getElementById("DIV_CHAT")!=null){document.getElementById("DIV_CHAT").innerHTML=oxmlHttp.responseText;oxmlHttp=null;}varscrollDiv=document.getElementById("DIV_CHAT");scrollDiv.scrollTop=scrollDiv.scrollHeight;}}以下SQLCREATETABLE命令可用于创建名为chat的数据库表。用户输入的所有信息都输入到数据库表中。创建表聊天(idbigintAUTO_INCREMENT,usernamevarchar(20),chatdatedatetime,msgvarchar(500),主键(id));兴趣点这段用于实现聊天应用程序的代码非常有趣。它可以被改进成为一个完整的HTTP聊天应用程序。创建应用程序的逻辑也非常简单。即使是初学者也不难理解。许可本文以及任何相关的源代码和文档均已获得代码项目开放许可(CPOL)许可。翻译链接:http://www.codeceo.com/article/php-chart-app.html英文原文:ChatApplicationinPHP".$line["cdt"]." ".$line["username"].": ".$line["msg"]."
