收藏本站 
广告服务 
网站地图 
>> 本频道近100000余篇各类电脑技术、网络技术、软件技术、网页及平面设计等方面的电脑教程,我们的原则:不是精华拒不收录!
先飞电脑技术网技术文章网络编程C#编程
网络编程 | 网站建设 | 网络技术 | 设计教程 | 软件教学 | 程序开发 | 数据库开发 | 教育认证 | 硬件维护 | 媒体动画 | 机械电子 |

用.Net处理XmlHttp发送异步请求

[ 作者:佚名    转贴自:网络转载    阅读次数:28    更新时间:2007-10-1 16:29:00   录入:刘光勇 ]        
    我们要达到的目的是点击按钮,获得服务器的当前时间,aspx的html如下:
Html
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Linkedu.Web.WebWWW.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>测试</title>
    <script language="javascript" src="javascript/prototype/extras-array.js"></script>
   <script language="javascript" src="javascript/xmlHttp.js"></script>
   <script language="javascript" src="javascript/eventRouter.js"></script>
    <script language="javascript" src="Default.js"></script>
    <script language="javascript">
 
    </script>
</head>
<body>
    <form id="form1" runat="server">
        用Post方式获得服务器的当前时间
        <input id="btnTestPost" type="button" value="Post" />
        用Get方式获得服务器的当前时间
        <input id="btnTestGet" type="button" value="Get" />
        <div id="divResult"></div>
</form>
</body>
</html>

要用javascript 发送xmlHttp 请求必须解决的问题是跨浏览器的支持。我们把xmlHttp的发送封装在一个javascript对象中,同时在这个对象中解决了跨浏览器支持的问题。代码如下:

xmlHttp对象
/**//*
url-loading object and a request queue built on top of it
*/

/**//* namespacing object */
var net=new Object();

net.READY_STATE_UNINITIALIZED=0;
net.READY_STATE_LOADING=1;
net.READY_STATE_LOADED=2;
net.READY_STATE_INTERACTIVE=3;
net.READY_STATE_COMPLETE=4;


/**//*--- content loader object for cross-browser requests ---*/
net.xmlHttp=function(url, onload, params, method, contentType, onerror){
  this.req=null;
  this.onload=onload;
  this.onerror=(onerror) ? onerror : this.defaultError;
  if(typeof(method) == "undefined" || method == null)
  {
    method = "POST";
  }
  this.loadXMLDoc(url, params, method, contentType);
}

net.xmlHttp.prototype.loadXMLDoc=function(url, params, method, contentType){
  if (!method){
    method="GET";
  }
  if (!contentType && method=="POST"){
    contentType='application/x-www-form-urlencoded';
  }
  if (window.XmlHttpRequest){
    this.req=new XmlHttpRequest();
  } else if (window.ActiveXObject){
    this.req=new ActiveXObject("Microsoft.xmlHttp");
  }
  if (this.req){
    try{
      var loader=this;
      this.req.onreadystatechange=function(){
        net.xmlHttp.onReadyState.call(loader);
      }
      this.req.open(method,url,true);
      if (contentType){
        this.req.setRequestHeader('Content-Type', contentType);
      }
      this.req.send(params);
    }catch (err){
      this.onerror.call(this);
    }
  }
}


net.xmlHttp.onReadyState=function(){
  var req=this.req;
  var ready=req.readyState;
  if (ready==net.READY_STATE_COMPLETE){
    var httpStatus=req.status;
    if (httpStatus==200 || httpStatus==0){
      this.onload.call(this);
    }else{
      this.onerror.call(this);
    }
  }
}

net.xmlHttp.prototype.defaultError=function(){
  alert("error fetching data!"
    +"\n\nreadyState:"+this.req.readyState
    +"\nstatus: "+this.req.status
    +"\nheaders: "+this.req.getAllResponseHeaders());
}

 

下面开始写发送xmlHttp请求的代码:

default.js
//全局xmlHttp对象
var cobj;

/**//* Post begin*/
//绑定Post发送xmlHttp事件到btnTestPost
function loadTestPost()
{
   var iobj = document.getElementById("btnTestPost");
   //btnTestPost按钮监听的绑定
   var clickRouter=new jsEvent.EventRouter(iobj,"onclick");
   clickRouter.addListener(btnTestPostClick);
}
function btnTestPostClick()
{   // open参数 url, onload, params, method, contentType, onerror
    cobj = new net.xmlHttp("DefaultHandler.ashx",dealResult, "<T/>", "POST");
}
/**//* Post end*/


/**//* Get begin*/
//绑定Get发送xmlHttp事件到btnTestGet
function loadTestGet()
{
   var iobj = document.getElementById("btnTestGet");
   //btnTestGet按钮监听的绑定
   var clickRouter=new jsEvent.EventRouter(iobj,"onclick");
   clickRouter.addListener(btnTestGetClick);
}
function btnTestGetClick()
{   //  open参数 url, onload, params, method, contentType, onerror
    cobj = new net.xmlHttp("DefaultHandler.ashx?T=1",dealResult, null, "GET");
}
/**//* Get end*/

 

function dealResult()
{   
    var dobj = document.getElementById("divResult");
    dobj.innerHTML =  cobj.req.responseXML.text;
}


window.onload = function()
{
    //绑定Post发送xmlHttp事件到btnTestPost
    loadTestPost();
    //绑定Get发送xmlHttp事件到btnTestGet
    loadTestGet();
};

最后是.net处理xmlHttp的代码
.net 处理xmlHttp请求
public class DefaultHandler : IHttpHandler
    {
        protected XmlDocument _xmlResult;

        public void ProcessRequest(HttpContext context)
        {
            if (context.Request["T"] != null)
            {//GET xmlhttp测试
                context.Response.ContentType = "text/xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.LoadXml(string.Format(@"<time>GET:{0}</time>", System.DateTime.Now));
                xmlDoc.Save(context.Response.OutputStream);
                context.Response.End();
            }
            else
            {//POST xmlhttp测试
                context.Response.ContentType = "text/xml";
                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(context.Request.InputStream);
                if (xmlDoc.DocumentElement.Name == "T")
                {
                    xmlDoc.LoadXml(string.Format(@"<time>POST:{0}</time>", System.DateTime.Now));
                    xmlDoc.Save(context.Response.OutputStream);
                    context.Response.End();
                }
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }

文章首页【加入到收藏夹】告诉好友】【打印此文】【关闭窗口
  版权声明:本站提供的“用.Net处理XmlHttp发送异步请求”版权归文章所有者,转载请注明出处!
 ·上一篇文章:C#中使用存储过程中的返回值      ·下一篇文章:C#多线程集合数据同步的实现方法
相关文章
·用.Net处理XmlHttp发送异步请求[28]
·使用.NET实现你的IP切换器[19]
·在SQL Server中使用CLR调用.NET方法[14]
·SQL Server中使用CLR调用.NET方法[58]
·讲解用.NET编写串口程序的一点心得[91]
网站主页 | 收藏本页 | 联系我们 | 广告服务 | 站点地图 | 会员注册 | 招聘信息 | 内容指正

联系QQ:先飞电脑技术网站事务联系QQ,点击可以直接留言. 32933427 电话:13710542091 [世界排名] 鄂ICP备05005890号 先飞电脑教程网