一个简单的Asp+ajax聊天室(一)

用Asp+ajax来做一个简单的聊天室,今天先做发送消息部分

前台代码:

<! DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
< meta http-equiv ="Content-Type" content ="text/html;charset=utf-8" />
< title > 无问的聊天室 </ title >
< script type ="text/javascript" src ="chat.js" ></ script >
< style type ="text/css" >
<!--
.chat
{ border : #6666661pxsolid ; display : block ; margin-left : 5px ; margin-right : 5px ; height : 680px ; padding : 10px ; }
-->
</ style >
</ head >

< body >
< H3 > 无的聊天室 </ H3 >
< div id ="chat" class ="chat" >
<!-- 这里显示聊天信息 -->
</ div >
< form id ="frmSend" name ="frmSend" onsubmit ="sendMess();returnfalse;" >
< input name ="username" type ="text" id ="username" value ="无问" size ="10" />
< input name ="mess" type ="text" id ="mess" size ="100" />
< input type ="submit" value ="send" id ="submitsend" name ="submitsend" />
</ form >
</ body >
</ html >

JS代码chat.js:

// 通过封装getAjax()方法创建XMLHTTPRequest对象
function getAjax()
{
var ajax = false ;
try {
ajax
= new ActiveXObject( " Msxml2.XMLHTTP " );
}
catch (e){
try {
ajax
= new ActiveXObject( " Microsoft.XMLHTTP " );
}
catch (E){
ajax
= false ;
}
}
if ( ! ajax && typeof XMLHttpRequest != ' undefined ' ){
ajax
= new XMLHttpRequest();
}
return ajax;
}

var getMessReq = getAjax(); // 获取消息的XMLHTTPRequest对象
var sendMessReq = getAjax(); // 发送消息的XMLHTTPRequest对象

// 发送消息的方法
function sendMess()
{
// 如果消息为空给出提示并返回
if (document.getElementById( " mess " ).value == "" ){
alert(
" Youhavenotenteredamessage! " );
return ;
}

// 判断上次发送消息的状态,4:已发送,0:未发送
if (sendMessReq.readyState == 4 || sendMessReq.readyState == 0 ){
// 发送消息的服务器端地址
var sendUrl = " send.asp?username= " + escape(document.getElementById( " username " ).value) + " &mess= " + escape(document.getElementById( " mess " ).value);
sendMessReq.open(
" POST " ,sendUrl, true ); // 建立请求连接
sendMessReq.onreadystatechange = function (){ // 发送状态改变后调用的方法
// 还有一些代码明天再写
}

sendMessReq.send(
null ); // 发送请求
document.getElementById( " mess " ).value = "" ; // 设置消息框为空
}
}

保存消息的服务器端代码send.asp:

<% @LANGUAGE = " VBSCRIPT " CODEPAGE = " 65001 " %>
<!-- #includefile = " conn.asp " -->
<%
dimusername,mess
username
= Trim(Request.QueryString( " username " ))
mess
= Trim(Request.QueryString( " mess " ))
conn.execute(
" insertintomessage(messtext,username)values(' " & mess & " ',' " & username & " ') " )
conn.close()
set conn = Nothing
%>

数据表:message

一个简单的Asp+ajax聊天室(一)

注意:要为date字段设置一个默认值:getDate()

请天就到这儿吧,明天接着写显示消息的部分,夜了,要睡觉觉了

你可能感兴趣的:(JavaScript,Ajax,css,VBScript,asp)