jQuery实现简单聊天室
自从看了jQuery后,顿时感觉其的确很简单易学。下面就一把自己写的一个简易的聊天室程序写出来。
主要就是利用jQuery的ajax,然后,别的其实也没什么了。先上client端的程序吧。
$(function(){ timestamp=0; updateMsg(timestamp); $('button').click(function(){//重点是这里,从这里向服务器端发送数据 $.post('chat.php',{ 'message':$('#msg').val(), 'name':$('#name').val(), 'timestamp':timestamp },function(xml){ $('#msg').val(''); addMessage(xml); }); returnfalse; }); $('#name').blur(function(){//仅仅用来控制名字输入框的背景 if($('#name').val()){ $(this).css({"background":"url(images/background.jpg)","border":"2pxdashed#fff"}); }; }); $('#name').click(function(){ $(this).css({"background":"#fff","border":"2pxsolid#fff"}); }) }); //updatemessage functionupdateMsg(timestamp){//从服务器端更新聊天数据,并载入吧 $.post('chat.php',{'timestamp':timestamp},function(xml){ $('#loading').remove(); addMessage(xml); }); setTimeout('updateMsg(timestamp);',1000);//1s刷新一次信息 } functionaddMessage(xml){//解析xml,并添加到页面内 if($('status',xml).text()==2){ return; }; timestamp=$('timestamp',xml).text(); $('message',xml).each(function(){ varauthor=$('author',this).text(); varcontent=$('content',this).text(); vartime=$('time',this).text(); varhtmlcode=' '+author+':'; $('#messageWindow').append(htmlcode); scrollToBottom(); }); } functionscrollToBottom(){//控制滚动条一直显示在底部 varheight=document.getElementById('messageWindow').scrollHeight; if(height>$('#messageWindow').scrollTop()){ $('#messageWindow').scrollTop(height); } }'+content+'