c#实现web ajax通讯的例子,无第三方插件、脚本,无ajax.js类库,c#实现。运行IE9以上,IIS,.net 4.0,代码其他.net版本也可以编译通过。非IE浏览器用极速模式浏览,因为兼容模式支持IE的版本太低,除火狐外,其他浏览器均正常显示。例子包括:自定义滚动条、css3绘图、c#实现ajax原理等。做了“”频道“部分,其他部分原理相同就没做了。最右侧未放功能,空白。为了便于学习,没用数据库,全在缓存中进行数据交互,把代码里127.0换成你的地址。多找几台机子,配好iis,试试。 Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); //不使用浏览器缓存
string[] Msg_bubble = new string[3];
string[] Msg_bubbleRight = new string[3];
ArrayList vlist = new ArrayList(); //引用类,内容
ArrayList ulist = new ArrayList(); //引用类,用户名
ArrayList tlist = new ArrayList(); //引用类,内容
ArrayList klist = new ArrayList(); //引用类,内容
/////////////////////////////////////
string strCount = ""; //存放消息
int nowId = 0; //消息总数
string type = Request.QueryString["type"].ToString(); //取得传递页面参数“type”
string uid = Microsoft.JScript.GlobalObject.unescape(Request.QueryString["uid"].ToString()); //解码
if (Cache.Get("num_info") != null) //取得消息总数
{
nowId = (int)Cache.Get("num_info"); //从缓存中取得数目
}
if (type == "send") //发送消息
{
string Msg = Request.Form["msg"].ToString(); //取得post传递的内容
Msg = HttpUtility.HtmlDecode(Msg); //解码
Msg = Msg.Replace("\r\n", "<br/>");
MsgList.msglist.Add(Msg); //将内容添加到MsgList类中
Cache.Insert("msg_info", MsgList.msglist); //所有内容写入缓存
MsgList.userlist.Add(uid); //将当前用户名添加到MsgList类中
Cache.Insert("user_info", MsgList.userlist); //所有用户名写入缓存
MsgList.timelist.Add(DateTime.Now.ToString("H:m")); //time
Cache.Insert("time_info", MsgList.timelist); //time
MsgList.takelist.Add(Request.QueryString["taker"].ToString()); //对象
Cache.Insert("take_info", MsgList.takelist); //time
vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
tlist = (ArrayList)Cache.Get("time_info"); //缓存取得时间
klist = (ArrayList)Cache.Get("take_info"); //缓存取得对象
for (int i = 0; i < nowId 1; i ) //将全部内容放入字符串
{
if ((string)klist[i] == Request.QueryString["taker"].ToString())
{
if ((string)ulist[i] == uid) //如果是本人
{
strCount = strCount Msg_bubbleRight[0] "<span style='color:#bbb'>" ulist[i] " " tlist[i] "</span>" Msg_bubbleRight[1] vlist[i] Msg_bubbleRight[2];
}
else
{
strCount = strCount Msg_bubble[0] "<span style='color:#bbb'>" ulist[i] " " tlist[i] "</span>" Msg_bubble[1] vlist[i] Msg_bubble[2];
}
strCount = strCount "<br/>";
}
}
MsgList.idNum ;
Cache.Insert("num_info", MsgList.idNum); //序号总数
}
///////////////////////////////////////////////////////////////////////////////////////////////
if (type == "get") //取得全部消息
{
vlist = (ArrayList)Cache.Get("msg_info"); //缓存中取得全部内容
ulist = (ArrayList)Cache.Get("user_info"); //缓存取得全部用户
tlist = (ArrayList)Cache.Get("time_info"); //缓存取得全部用户
klist = (ArrayList)Cache.Get("take_info"); //缓存取得对象
for (int i = 0; i < nowId; i ) //将全部内容放入字符串
{
if ((string)klist[i] == Request.QueryString["taker"].ToString())
{
if ((string)ulist[i] == uid) //如果是本人
{
strCount = strCount Msg_bubbleRight[0] "<span style='color:#bbb'>" ulist[i] " " tlist[i] "</span>" Msg_bubbleRight[1] vlist[i] Msg_bubbleRight[2];
}
else
{
strCount = strCount Msg_bubble[0] "<span style='color:#bbb;margin-right:20px;'>" ulist[i] " " tlist[i] "</span>" Msg_bubble[1] vlist[i] Msg_bubble[2];
}
strCount = strCount "<br/>";
}
}
}
Response.Write(strCount); //显示到内容框里面
aspx中定义<script type="text/javascript">
var username = null, msg_Len = 0; //设置用户、显示内容长度
function loadXMLDoc(type,sendHtml)
{
var xmlhttp;
if (username != null)
{
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("message-take").innerHTML = xmlhttp.responseText;
}
}
if (type == "get") { //取得数据信息
xmlhttp.open("POST", "http://127.0.0.1/receive.aspx?type=get" "&uid=" escape(username) "&taker=" document.getElementById('take-class').value, true); //传递页面
xmlhttp.send();
} else if (type == "send") { //发送数据信息
var nowTime = new Date().getTime();
xmlhttp.open("POST", "http://127.0.0.1/receive.aspx?type=send&timeStamp=" nowTime "&uid=" escape(username) "&taker=" document.getElementById('take-class').value, true);
sendHtml = html2Escape(sendHtml); //转码,能显示html格式
var queryString = "msg=" escape(sendHtml); //发送的内容
xmlhttp.setRequestHeader("Content-Length", queryString.lenght); //发送的内容长度
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); //发送的内容编码
xmlhttp.send(queryString);
}
ScrolltoBottom(); //滚动保持最底部
setTimeout("loadXMLDoc('get','')", 1000); //1秒执行一次
}
}
function loadXMLNum() {
var xmlhttp_num;
if (username != null) {
if (window.XMLHttpRequest) {
xmlhttp_num = new XMLHttpRequest();
}
else {
xmlhttp_num = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp_num.onreadystatechange = function () {
if (xmlhttp_num.readyState == 4 && xmlhttp_num.status == 200) {
document.getElementById("num_flush").innerHTML = xmlhttp_num.responseText;
}
}
xmlhttp_num.open("POST", "http://127.0.0.1/infonum.aspx", true);
xmlhttp_num.send(null);
setTimeout("loadXMLNum()", 2000); //2秒执行一次
}
}
function InitUser(uname)
{
username = uname; //初始化用户名
}
function html2Escape(sHtml) { //转码
return sHtml.replace(/[<>&"]/g, function (c) { return { '<': '<', '>': '>', '&': '&', '"': '"' }[c]; });
}
function escape2Html(str) { //转码
var arrEntities = { 'lt': '<', 'gt': '>', 'nbsp': ' ', 'amp': '&', 'quot': '"' };
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function (all, t) { return arrEntities[t]; });
}
function ScrolltoBottom() //设置滚动条到底部
{
var oContainer = document.getElementById("take-message-scroll"),
osend_msg = document.getElementById("message-take"),
oScroll_track = document.getElementById("ScrollBar-TakeTrack"),
oScroll_arrow = document.getElementById("ScrollBar-TakeArrow");
if (msg_Len !== osend_msg.innerHTML.length) { //内容长度改变,设置滚动条
if (osend_msg.scrollHeight >=450) {
oScroll_arrow.style.top = (oScroll_track.offsetHeight - oScroll_arrow.offsetHeight) 'px';
osend_msg.style.top = -(osend_msg.offsetHeight - oContainer.offsetHeight) 'px';
} else {
oScroll_arrow.style.top = 0 "px";
osend_msg.style.top = 0 "px";
}
msg_Len = osend_msg.innerHTML.length; //更新长度
}
}
function Scroll_Event(mainObj,sendObj,Track,Arrow) //鼠标滚动事件
{
var oContainer = document.getElementById(mainObj),
osend_msg = document.getElementById(sendObj),
oScroll_track = document.getElementById(Track),
oScroll_arrow = document.getElementById(Arrow);
addEvent(osend_msg, 'mousewheel', mousewheel);
addEvent(osend_msg, 'DOMMouseScroll', mousewheel);
addEvent(oScroll_track, 'mousewheel', mousewheel);
addEvent(oScroll_track, 'DOMMouseScroll', mousewheel);
oScroll_arrow.onmousedown = function (e) {
e = e || event;
var disY = e.clientY - this.offsetTop;
if (oScroll_arrow.setCapture) {
oScroll_arrow.onmousemove = fnMove;
oScroll_arrow.onmouseup = fnUp;
oScroll_arrow.setCapture();
} else {
document.onmousemove = fnMove;
document.onmouseup = fnUp;
}
function fnMove(ev) {
ev = ev || event;
var t = ev.clientY - disY;
setTop(t);
};
function fnUp() {
this.onmousemove = null;
this.onmouseup = null;
if (this.releaseCapture) {
this.releaseCapture();
}
};
return false;
};
function setTop(t) {
var down = oScroll_track.offsetHeight - oScroll_arrow.offsetHeight;
if (t < 0) {
t = 0;
} else if (t > down) {
t = down
}
oScroll_arrow.style.top = t 'px';
var scale = t / down;
osend_msg.style.top = -(osend_msg.offsetHeight - oContainer.offsetHeight) * scale 'px';
}
function addEvent(obj, oEvent, fn) {
if (obj.attachEvent) {
obj.attachEvent('on' oEvent, fn);
} else {
obj.addEventListener(oEvent, fn, false);
}
}
function mousewheel(e) {
var ev = e || event, bDown = false;
bDown = ev.wheelDelta ? ev.wheelDelta < 0 : ev.detail > 0;
if (bDown) {
setTop(oScroll_arrow.offsetTop 10);
} else {
setTop(oScroll_arrow.offsetTop - 10);
}
if (e.preventDefault) {
e.preventDefault();
}
return false;
}
}
function InsertMessageInfo(obj,html,taker,num) {
document.getElementById(obj).innerHTML = html "<span class=message-tool-ing style=float:right>" getNowFormatDate() "<span>";
Scroll_Event("take-message-scroll", "message-take", "ScrollBar-TakeTrack", "ScrollBar-TakeArrow");
clear_txt('abcEdit_mid');
document.getElementById('abcEdit_mid').contentEditable = true;
document.getElementById('take-class').value = taker;
document.getElementById('num-class').value = num;
loadXMLDoc('get', '');///
}
......................................................................................
评论