Implement a simple Ajax-based chat room
1. Program Homepage
Include_once ("server1.server. php"); # servidor para xajax
$ Xajax-> printjavascript ();
?>
2 scripts
-- Chat room
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. Server Side
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 for displaying messages
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 $ TMP. = $ chats [$ I] ['Nick ']. ":". $ chats [$ I] ['word']."
";
}
// Delete old data retains only 15 items
$ 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 ();
}
// No form submission program. Pay special attention to the use of iconv to restore the URL encoding.
Function speak ($ formdata ){
Global $ db, $ now;
$ Objresponse = new xajaxresponse ();
$ Words = iconv ("UTF-8", "GBK", $ formdata ['word']);
$ 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 ();
?>
Trackback: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 510970