简单聊天室(Ajax)(jQuery1.4+ashx)
唉.一个星期上班的最后一天.
项目也快完成了.就是在那里改一下BUG
只是公司里电脑不能上网,看着好久没有策QQ了
所以今天就想做一个简单一点的聊天室,
只要能进去群策就OK了
首先上图(项目的架构)
用的工厂模式做的再加上最新的jQuery1.4
只不过公司里都是用的VS2005.
所以环境就只能用VS2005+Sql2005
下面是JavaScript代码,
主要功能就是去请求数据和绑定数据了
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<script language="javascript" type="text/javascript">
//配置对角
var _config = new Object({
url:"AjaxPages/AjaxChatRequest.ashx",
async:false,
dataType:"json",
type:"POST",
msgID:<%=Application["maxCount"].ToString()%>-1,
msgName:"Guest",
msgIP:"<%=Request.UserHostAddress%>"
});
var ChatMsgObjArray = new Array()
ChatMsgObj = function(){
this.msgID;
this.msgName;
this.msgIP;
this.msgTime;
this.msgText;
}
//开始运行的
$(document).ready(function(){
ChangeMsgName();
GetMsgJsonInfo();
});
function GetMsgJsonInfo()
{
//alert(_config.msgID);
GetMsgIDToLastJson(_config.msgID);
}
//修改名字
function ChangeMsgName()
{
var _msgName=prompt("请输入你的名字","Guest");
if(_msgName!="" && _msgName!=null)
{
_msgName=_msgName.substring(0,8);
_config.msgName=_msgName;
}
}
//得到一个ID后的所有消息
function GetMsgIDToLastJson(LastID)
{
$.ajax({
url:_config.url,
data:{"_type":"GetLastToEnd","LastID":LastID},
async:_config.async,
dataType:_config.dataType,
type:_config.type,
success:function(data){
//SetSaveObjArray(data);
BindObjJson(data);
if(data.length!=0)
{
_config.msgID=data[data.length-1]["msgID"];
}
setTimeout("GetMsgJsonInfo()",1000);
}
});
}
//保存实体对象
function SetSaveObjArray(data)
{
for(var i=0;i<data.length;i++)
{
var _obj = new ChatMsgObj();
_obj.msgID=data[i]["msgID"];
_obj.msgName=data[i]["msgName"];
_obj.msgIP=data[i]["msgIP"];
_obj.msgTime=data[i]["msgTime"];
_obj.msgText=data[i]["msgText"];
ChatMsgObjArray.push(_obj);
}
}
//绑定对角
function BindObjJson(data)
{
for(var i=0;i<data.length;i++)
{
var _html = "<div class=\"ShowMsg\"><div><span class=\"ShowSpanName\">"+data[i]["msgName"]+"</span><span class=\"ShowSpanIP\">"+data[i]["msgIP"]+"</span><span class=\"ShowSpanTime\">"+data[i]["msgTime"]+"</span></div><div class=\"ShowMsgText\"><p id=\"ShowMsg_P"+data[i]["msgID"]+"\"></p></div></div>";
$("#Main_Show_Msg").append(_html);
$("#ShowMsg_P"+data[i]["msgID"]).text(data[i]["msgText"]);
getScrollToEnd();
}
}
//发送对象
function SendObj()
{
var _obj = new ChatMsgObj()
_obj.msgName=_config.msgName;
_obj.msgIP=_config.msgIP;
_obj.msgTime=Date().toString();
_obj.msgText=$("#msgText_textarea").val();
if(_obj.msgText=="")
{
return;
}
$.post(_config.url,{"_type":"SendChatMsg","msgName":_obj.msgName,"msgIP":_obj.msgIP,"msgTime":_obj.msgTime,"msgText":_obj.msgText},function(data){
$("#msgText_textarea").val("");
document.getElementById("msgText_textarea").focus();
},_config.dataType);
}
//移动流动条
function getScrollToEnd()
{
var MsgDiv=document.getElementById("Main_Show_Msg");
MsgDiv.doScroll("scrollbarPageDown");
}
</script>
//配置对角
var _config = new Object({
url:"AjaxPages/AjaxChatRequest.ashx",
async:false,
dataType:"json",
type:"POST",
msgID:<%=Application["maxCount"].ToString()%>-1,
msgName:"Guest",
msgIP:"<%=Request.UserHostAddress%>"
});
var ChatMsgObjArray = new Array()
ChatMsgObj = function(){
this.msgID;
this.msgName;
this.msgIP;
this.msgTime;
this.msgText;
}
//开始运行的
$(document).ready(function(){
ChangeMsgName();
GetMsgJsonInfo();
});
function GetMsgJsonInfo()
{
//alert(_config.msgID);
GetMsgIDToLastJson(_config.msgID);
}
//修改名字
function ChangeMsgName()
{
var _msgName=prompt("请输入你的名字","Guest");
if(_msgName!="" && _msgName!=null)
{
_msgName=_msgName.substring(0,8);
_config.msgName=_msgName;
}
}
//得到一个ID后的所有消息
function GetMsgIDToLastJson(LastID)
{
$.ajax({
url:_config.url,
data:{"_type":"GetLastToEnd","LastID":LastID},
async:_config.async,
dataType:_config.dataType,
type:_config.type,
success:function(data){
//SetSaveObjArray(data);
BindObjJson(data);
if(data.length!=0)
{
_config.msgID=data[data.length-1]["msgID"];
}
setTimeout("GetMsgJsonInfo()",1000);
}
});
}
//保存实体对象
function SetSaveObjArray(data)
{
for(var i=0;i<data.length;i++)
{
var _obj = new ChatMsgObj();
_obj.msgID=data[i]["msgID"];
_obj.msgName=data[i]["msgName"];
_obj.msgIP=data[i]["msgIP"];
_obj.msgTime=data[i]["msgTime"];
_obj.msgText=data[i]["msgText"];
ChatMsgObjArray.push(_obj);
}
}
//绑定对角
function BindObjJson(data)
{
for(var i=0;i<data.length;i++)
{
var _html = "<div class=\"ShowMsg\"><div><span class=\"ShowSpanName\">"+data[i]["msgName"]+"</span><span class=\"ShowSpanIP\">"+data[i]["msgIP"]+"</span><span class=\"ShowSpanTime\">"+data[i]["msgTime"]+"</span></div><div class=\"ShowMsgText\"><p id=\"ShowMsg_P"+data[i]["msgID"]+"\"></p></div></div>";
$("#Main_Show_Msg").append(_html);
$("#ShowMsg_P"+data[i]["msgID"]).text(data[i]["msgText"]);
getScrollToEnd();
}
}
//发送对象
function SendObj()
{
var _obj = new ChatMsgObj()
_obj.msgName=_config.msgName;
_obj.msgIP=_config.msgIP;
_obj.msgTime=Date().toString();
_obj.msgText=$("#msgText_textarea").val();
if(_obj.msgText=="")
{
return;
}
$.post(_config.url,{"_type":"SendChatMsg","msgName":_obj.msgName,"msgIP":_obj.msgIP,"msgTime":_obj.msgTime,"msgText":_obj.msgText},function(data){
$("#msgText_textarea").val("");
document.getElementById("msgText_textarea").focus();
},_config.dataType);
}
//移动流动条
function getScrollToEnd()
{
var MsgDiv=document.getElementById("Main_Show_Msg");
MsgDiv.doScroll("scrollbarPageDown");
}
</script>
下面呢就是处理请求(ashx)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class AjaxChatRequest : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request.Form["_type"] != null)
{
switch (context.Request.Form["_type"].ToString())
{
case "GetLastToEnd": GetLastToEnd(context); break;
case "SendChatMsg": SendChatMsg(context); break;
default: break;
}
}
}
/// <summary>
/// 发送一个实体JOSN对象数据
/// </summary>
/// <param name="context"></param>
private void GetLastToEnd(HttpContext context)
{
int LastID;
bool isNum = int.TryParse(context.Request.Form["LastID"].ToString(), out LastID);
int maxCount = (int)context.Application["maxCount"];
if (isNum && LastID != maxCount)
{
B_chatMsg bcm = new B_chatMsg();
string whereStr = "msgID > " + LastID.ToString();
List<chatMsg> ListCM = bcm.GetModelList(whereStr);
string ResJsonStr = JsonConvert.SerializeObject(ListCM);
context.Response.Write(ResJsonStr);
}
else
{
context.Response.Write("[]");
}
}
/// <summary>
/// 保存一个信息
/// </summary>
/// <param name="context"></param>
private void SendChatMsg(HttpContext context)
{
chatMsg cm = new chatMsg();
cm.msgIP = context.Request.Form["msgIP"].ToString();
cm.msgName = context.Request.Form["msgName"].ToString();
cm.msgText = context.Request.Form["msgText"].ToString();
cm.msgTime = DateTime.Now;
B_chatMsg bcm = new B_chatMsg();
int addMsgID = bcm.Add(cm);
context.Application.Lock();
context.Application["maxCount"] = addMsgID;
context.Application.UnLock();
//cm = bcm.GetModel(addMsgID);
cm.msgID = addMsgID;
context.Response.Write(JsonConvert.SerializeObject(cm));
}
public bool IsReusable
{
get
{
return false;
}
}
}
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
if (context.Request.Form["_type"] != null)
{
switch (context.Request.Form["_type"].ToString())
{
case "GetLastToEnd": GetLastToEnd(context); break;
case "SendChatMsg": SendChatMsg(context); break;
default: break;
}
}
}
/// <summary>
/// 发送一个实体JOSN对象数据
/// </summary>
/// <param name="context"></param>
private void GetLastToEnd(HttpContext context)
{
int LastID;
bool isNum = int.TryParse(context.Request.Form["LastID"].ToString(), out LastID);
int maxCount = (int)context.Application["maxCount"];
if (isNum && LastID != maxCount)
{
B_chatMsg bcm = new B_chatMsg();
string whereStr = "msgID > " + LastID.ToString();
List<chatMsg> ListCM = bcm.GetModelList(whereStr);
string ResJsonStr = JsonConvert.SerializeObject(ListCM);
context.Response.Write(ResJsonStr);
}
else
{
context.Response.Write("[]");
}
}
/// <summary>
/// 保存一个信息
/// </summary>
/// <param name="context"></param>
private void SendChatMsg(HttpContext context)
{
chatMsg cm = new chatMsg();
cm.msgIP = context.Request.Form["msgIP"].ToString();
cm.msgName = context.Request.Form["msgName"].ToString();
cm.msgText = context.Request.Form["msgText"].ToString();
cm.msgTime = DateTime.Now;
B_chatMsg bcm = new B_chatMsg();
int addMsgID = bcm.Add(cm);
context.Application.Lock();
context.Application["maxCount"] = addMsgID;
context.Application.UnLock();
//cm = bcm.GetModel(addMsgID);
cm.msgID = addMsgID;
context.Response.Write(JsonConvert.SerializeObject(cm));
}
public bool IsReusable
{
get
{
return false;
}
}
}
其中用了Newtonsoft的Json处理类
下面的图中界面,我不是做美工的.所以界面就不怎么样了
呵,完全处于个人爱好,请大家不要见怪
虽然现在做得比效好的腾迅用的长连接
只不过我只要在我们局域网内玩.
不要做那么大.有高手可以一起来研究一下长连接技术
祝大家周未开心
都看完了,你确定不点个赞再走?