核心逻辑
在定义应用程序的核心功能之前,先来看一看聊天应用程序的基本外观,如以下截图所示:
通过聊天窗口底部的输入框输入聊天文本。点击Send按钮,就开始执行函数set_chat_msg。这是一个基于Ajax的函数,因此无需刷新页面就可以将聊天文本发送到服务器。程序在服务器中执行chat_send_ajax.php以及用户名和聊天文本。
//
// Set Chat Message
//
function set_chat_msg()
{
if(typeof XMLHttpRequest != "undefined")
{
oxmlHttpSend = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
oxmlHttpSend = new ActiveXObject("Microsoft.XMLHttp");
}
if(oxmlHttpSend == null)
{
alert("Browser does not support XML Http Request");
return;
}
var url = "chat_send_ajax.php";
var strname="noname";
var strmsg="";
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 = "";
}
$result = mysql_query($sql);
if(!$result)
{
throw new Exception('Query failed: ' . mysql_error());
exit();
}
为了接收来自数据库表中所有用户的聊天消息,timer函数被设置为循环5秒调用以下的JavaScript命令,即每隔5秒时间执行get_chat_msg函数。
var t = setInterval(function(){get_chat_msg()},5000);
get_chat_msg是一个基于Ajax的函数。它执行chat_recv_ajax.php程序以获得来自于数据库表的聊天信息。在 onreadystatechange属性中,另一个JavaScript 函数get_chat_msg_result被连接起来。在返回来自于数据库表中的聊天消息的同时,程序控制进入到 get_chat_msg_result函数。
//
// General Ajax Call
//
var oxmlHttp;
var oxmlHttpSend;
function get_chat_msg()
{
if(typeof XMLHttpRequest != "undefined")
{
oxmlHttp = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
oxmlHttp = new ActiveXObject("Microsoft.XMLHttp");
}
if(oxmlHttp == null)
{
alert("Browser does not support XML Http Request");
return;
}
$sql = "SELECT *, date_format(chatdate,'%d-%m-%Y %r')
as cdt from chat order by ID desc limit 200";
$sql = "SELECT * FROM (" . $sql . ") as ch order by ID";
$result = mysql_query($sql) or die('Query failed: ' . mysql_error());