实现一个基于ajax的简易聊天室
1 程序主页面
<html>
<head>
<title>在线交流对话</title>
<META http-equiv=Content-Language content=zh-cn>
<META http-equiv=Content-Type content="text/html; charset=gb2312">
<?php
include_once("server1.server.php"); #servidor para XAJAX
$xajax->printJavascript();
?>
</head>
<body>
<div id=display>
</div>
<script language=javascript>
function reloaddisplay()
{
xajax_reloaddisplay();
}
setInterval(reloaddisplay,5000); //五秒钟自动读取最新的留言15条
</script>
<script language=javascript>
function onSubmit() {
xajax_speak(xajax.getFormValues("speakForm"));
}
</script>
<div id=speak>
<form id="speakForm" action="javascript:void(null);" onsubmit="onSubmit();">
<fieldset>
<legend>Please into your words here!</legend>
<label>Speak:</label>
<input type="text" name="words" id="words" size="40" maxlength="150" />
<input type="submit" value="enter"> //点击按钮时提交
<input type="hidden" name="nick" id="nick" value="guest" />
</fieldset>
</form>
</div>
</body>
</html>
2 脚本
-- 聊天室
CREATE TABLE TBL_CHAT (
nick varchar(10) NOT NULL default '',
words varchar(150) NOT NULL default '',
chattime bigint(20) unsigned NOT NULL default '0'
) TYPE=MyISAM;
3 服务器端
<?php
include 'include.php';
require("xajax.inc.php");
//extend response
class myXajaxResponse extends xajaxResponse
{
function addAddOption($sSelectId, $sOptionText, $sOptionValue)
{
$sScript = "var objOption = new Option('".$sOptionText."','".$sOptionValue."');";
$sScript .= "document.getElementById('".$sSelectId."').options.add(objOption);";
$this->addScript($sScript);
}
function addClearSelect($sSelectId)
{
$sScript .= "document.getElementById('".$sSelectId."').options.length = 0;";
$sScript .= "document.getElementById('".$sSelectId."').options.selectedIndex = 0;";
$this->addScript($sScript);
}
}
//显示留言的函数
function reloaddisplay(){
global $db,$now;
$objResponse = new xajaxResponse();
$tmp="";
$chats = $db->getAll($db->modifyLimitQuery("select * from ".TBL_CHAT." order by chattime desc", 0, 15));
for ($i = 0, $count = count($chats); $i < $count; $i++) {
$tmp.= $chats[$i]['nick'].":".$chats[$i]['words']."<br>";
}
//Delete old data 只保留15条信息
$nr = $db->getOne("select count(*) from ".TBL_CHAT);
if($nr > 15) {
$delnr = $nr - 15;
$db->query("delete from TBL_CHAT order by chattime asc limit $delnr)");
}
$objResponse->addAssign("display","innerHTML",$tmp);
return $objResponse->getXML();
}
//无提交表单程序,特别注意这里需要用iconv还原url的编码
function speak($formData){
global $db,$now;
$objResponse = new xajaxResponse();
$words = iconv("UTF-8","GBK",$formData['words']);
$nick = iconv("UTF-8","GBK",$formData['nick']);
if(strlen($words) > 0 && strlen($nick) > 0) {
$db->query("insert into ".TBL_CHAT." (nick, words,chattime) values ("
.$db->quote(stripslashes($nick)).", "
.$db->quote(stripslashes($words))
.", '$now')");
}
$objResponse->addClear("words","value");
return $objResponse->getXML();
}
$xajax = new xajax("server1.server.php","xajax_",false);
$xajax->registerFunction("reloaddisplay");
$xajax->registerFunction("speak");
$xajax->processRequests();
?>