用.Net處理xmlHttp傳送非同步請求

iDotNetSpace發表於2008-09-04

最近正在拜讀《Ajax in Action》這本書,運用書中知識,結合.net,寫了這篇用.net 處理xmlHttp傳送非同步請求的文章。

我們要達到的目的是點選按鈕,獲得伺服器的當前時間,aspx的html如下:

            Html
                        Inherits="Linkedu.Web.WebWWW.Default" %>
           
            BR>            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
           
            http://www.w3.org/1999/xhtml" >
           


            測試
           
           
           
           
           
           
           
           
           
           
            用Post方式獲得伺服器的當前時間
           
            用Get方式獲得伺服器的當前時間
           
           

           
           
           
           
 


要用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, "", "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(@"", 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(@"", System.DateTime.Now));
            xmlDoc.Save(context.Response.OutputStream);
            context.Response.End();
            }
            }
            }
           
            public bool IsReusable
            {
            get
            {
            return false;
            }
            }
            }
 

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-441796/,如需轉載,請註明出處,否則將追究法律責任。

相關文章