[CommunityServer]AJAX客户端说明,XMLHttpRequest对象

简介:
 在CommunityServer中运用了自己的AJAX机制,没有借助其他的辅助控件。其中客户的XMLHttpRequest对象的封装,就足以让人大饱眼福,在一般的浏览器其都能够运行AJAX。下面我们来学习学习这个咚咚,希望能给更多的人带来帮助。

  首先当然是要了解一下浏览器中的XMLHttp对象了:

  XMLHTTP方法: 
          备注:客户机可以使用XMLHTTP对象发送任意的HTTP请求,接受HTTP应答,还可以对应答的XML文档进行解析。 

          Open方法:初始化一个Msxml2.XMLHTTP请求,指定HTTP请求方式、URL以及鉴定信息。

         语法:
          Open( bstrMethod, bstrUrl, varAsync, bstrUser, bstrPassword ) 

         参数介绍:

         bstrMethod: 数据传送方式,即GET或POST。 
          bstrUrl: 服务网页的URL。 
          varAsync: 是否同步执行。缺省为True,即同步执行,但只能在DOM中实施同步执行。用中一般将其置为False,即异步执行。 
          bstrUser: 用户名,可省略。 
          bstrPassword:用户口令,可省略。 

         Send方法:发送HTTP请求到服务器,返回应答。 

         语法: 
         oXMLHttpRequest.send(varBody) 

        说明:此方法是否同步取决于Open方法的varAsync参数。如果设为True则为同步,调用立刻返回,如果设为False调用直到整个应答被接收了才返回。 

         setRequestHeader( bstrHeader, bstrvalue )
 
         bstrHeader:HTTP 头(header) 
         bstrvalue: HTTP 头(header)的值 

        如果Open方法定义为POST,可以定义表单方式上传: 
        xmlhttp.setRequestHeader( "Content-Type", "application/x-www-form-urlencoded") 

XMLHTTP属性: 

  onreadystatechange:在同步执行方式下获得返回结果的事件句柄。只能在DOM中调用。 
  responseBody: 结果返回为无符号整数数组。 
  responseStream: 结果返回为IStream流。 
  responseText : 结果返回为字符串。 
  responseXML: 结果返回为XML格式数据。

  运用这个原理也可以做网络小偷程序,网络爬虫应该就是应用这个东西来完成的吧,不过我没有做过,可能在不久的将来会制作个来玩玩,这里我们最主要的是看看CS中是如何封装他的:

 
  1 None.gif // Ajax Start
  2 ExpandedBlockStart.gif ///<summary>
  3InBlock.gif///创建回调对象,如果存在window.XMLHttpRequest()对象,则返回此对象,如果是IE则搜索Msxml2.XMLHTTP各个版本及Microsoft.XMLHTTP并创建对象返回。
  4ExpandedBlockEnd.gif///</summary>

  5 ExpandedBlockStart.gif function Ajax_GetXMLHttpRequest()  {
  6ExpandedSubBlockStart.gif    if (window.XMLHttpRequest) {
  7InBlock.gif        return new XMLHttpRequest();
  8ExpandedSubBlockStart.gif    }
 else {
  9ExpandedSubBlockStart.gif        if (window.Ajax_XMLHttpRequestProgID) {
 10InBlock.gif            return new ActiveXObject(window.Ajax_XMLHttpRequestProgID);
 11ExpandedSubBlockStart.gif        }
 else {
 12InBlock.gif            var progIDs = ["Msxml2.XMLHTTP.5.0""Msxml2.XMLHTTP.4.0""MSXML2.XMLHTTP.3.0""MSXML2.XMLHTTP""Microsoft.XMLHTTP"];
 13ExpandedSubBlockStart.gif            for (var i = 0; i < progIDs.length; ++i) {
 14InBlock.gif                var progID = progIDs[i];
 15ExpandedSubBlockStart.gif                try {
 16InBlock.gif                    var x = new ActiveXObject(progID);
 17InBlock.gif                    window.Ajax_XMLHttpRequestProgID = progID;
 18InBlock.gif                    return x;
 19ExpandedSubBlockStart.gif                }
 catch (e) {
 20ExpandedSubBlockEnd.gif                }

 21ExpandedSubBlockEnd.gif            }

 22ExpandedSubBlockEnd.gif        }

 23ExpandedSubBlockEnd.gif    }

 24InBlock.gif    return null;
 25ExpandedBlockEnd.gif}

 26 ExpandedBlockStart.gif ///<summary>
 27InBlock.gif///Ajax回调。
 28InBlock.gif///</summary>
 29InBlock.gif///<param name="type">调用服务端函数所在的类包括命名空间(如:NExplus.Controls.SiteHeader)。</param>
 30InBlock.gif///<param name="id">客户端所对应的标记的ID(如:<div id="ID"></div>)。</param>
 31InBlock.gif///<param name="method">服务端(方法)函数名称(被AjaxMethod标记)。</param>
 32InBlock.gif///<param name="args">传到服务器的字符串。</param>
 33InBlock.gif///<param name="clientCallBack">同步或异步回调。</param>
 34InBlock.gif///<param name="debugRequestText">调试/请求字符串。</param>
 35InBlock.gif///<param name="debugResponseText">调试/输出字符串。</param>
 36InBlock.gif///<param name="debugErrors">调试的错误信息。</param>
 37InBlock.gif///<param name="includeControlValuesWithCallBack">是否和控件及其值一起回调。</param>
 38ExpandedBlockEnd.gif///<param name="url">Url地址。</param>

 39 ExpandedBlockStart.gif function Ajax_CallBack(type, id, method, args, clientCallBack, debugRequestText, debugResponseText, debugErrors, includeControlValuesWithCallBack, url)  {
 40InBlock.gif    
 41InBlock.gif    if (!url)
 42ExpandedSubBlockStart.gif    {
 43InBlock.gif        url = window.location.href;
 44InBlock.gif        url = url.replace(/\#.*$/'');//去除URL中标签部分,即"#"之后的字符串。
 45InBlock.gif        //加入参数Ajax_CallBack并设为true,说明是AJAX回调。
 46InBlock.gif        if (url.indexOf('?'> -1)
 47InBlock.gif            url += "&Ajax_CallBack=true";
 48InBlock.gif        else
 49ExpandedSubBlockStart.gif        {
 50InBlock.gif            if (url.substr(url.length - 11== "/")
 51InBlock.gif                url += "default.aspx";
 52InBlock.gif                
 53InBlock.gif            url += "?Ajax_CallBack=true";
 54ExpandedSubBlockEnd.gif        }

 55ExpandedSubBlockEnd.gif    }

 56InBlock.gif
 57InBlock.gif    var x = Ajax_GetXMLHttpRequest();//取得XMLHttpRequest对象。
 58InBlock.gif    var result = null;
 59ExpandedSubBlockStart.gif    if (!x) {
 60ExpandedSubBlockStart.gif        result = "value":null"error""NOXMLHTTP"};
 61ExpandedSubBlockStart.gif        if (debugErrors) {
 62InBlock.gif            alert("error: " + result.error);
 63ExpandedSubBlockEnd.gif        }

 64ExpandedSubBlockStart.gif        if (clientCallBack) {
 65InBlock.gif            clientCallBack(result);
 66ExpandedSubBlockEnd.gif        }

 67InBlock.gif        return result;
 68ExpandedSubBlockEnd.gif    }

 69InBlock.gif
 70InBlock.gif    x.open("POST", url, clientCallBack ? true : false);//以Post方式打开对象,这样在服务端就可以用Request.Form获取参数。
 71InBlock.gif    x.setRequestHeader("Content-Type""application/x-www-form-urlencoded; charset=utf-8");
 72ExpandedSubBlockStart.gif    if (clientCallBack) {
 73InBlock.gif        //如果同步,判断状态,输出错误消息。
 74ExpandedSubBlockStart.gif        x.onreadystatechange = function() {
 75InBlock.gif            var result = null;
 76InBlock.gif        
 77ExpandedSubBlockStart.gif            if (x.readyState != 4{
 78InBlock.gif                return;
 79ExpandedSubBlockEnd.gif            }

 80InBlock.gif            
 81ExpandedSubBlockStart.gif            if (debugResponseText) {
 82InBlock.gif                alert(x.responseText);
 83ExpandedSubBlockEnd.gif            }

 84InBlock.gif            
 85InBlock.gif            try
 86ExpandedSubBlockStart.gif            {
 87InBlock.gif                var result = eval("(" + x.responseText + ")");
 88ExpandedSubBlockStart.gif                if (debugErrors && result.error) {
 89InBlock.gif                    alert("error: " + result.error);
 90ExpandedSubBlockEnd.gif                }

 91ExpandedSubBlockEnd.gif            }

 92InBlock.gif            catch (err)
 93ExpandedSubBlockStart.gif            {
 94InBlock.gif                if (window.confirm('The following error occured while processing an AJAX request: ' + err.message + '\n\nWould you like to see the response?'))
 95ExpandedSubBlockStart.gif                {
 96InBlock.gif                    var w = window.open();
 97InBlock.gif                    w.document.open('text/plain');
 98InBlock.gif                    w.document.write(x.responseText);
 99InBlock.gif                    w.document.close();
100ExpandedSubBlockEnd.gif                }

101InBlock.gif                
102InBlock.gif                result = new Object();
103InBlock.gif                result.error = 'An AJAX error occured.  The response is invalid.';
104ExpandedSubBlockEnd.gif            }

105InBlock.gif            
106InBlock.gif            clientCallBack(result);            
107ExpandedSubBlockEnd.gif        }

108ExpandedSubBlockEnd.gif    }

109InBlock.gif    var encodedData = "Ajax_CallBackType=" + type;
110ExpandedSubBlockStart.gif    if (id) {
111InBlock.gif        encodedData += "&Ajax_CallBackID=" + id.split("$").join(":");
112ExpandedSubBlockEnd.gif    }

113InBlock.gif    encodedData += "&Ajax_CallBackMethod=" + method;
114ExpandedSubBlockStart.gif    if (args) {
115ExpandedSubBlockStart.gif        for (var i in args) {
116InBlock.gif            encodedData += "&Ajax_CallBackArgument" + i + "=" + encodeURIComponent(args[i]);
117ExpandedSubBlockEnd.gif        }

118ExpandedSubBlockEnd.gif    }

119InBlock.gif    //如果加入控件,则加入控件数据。
120ExpandedSubBlockStart.gif    if (includeControlValuesWithCallBack && document.forms.length > 0{
121InBlock.gif        var form = document.forms[0];
122ExpandedSubBlockStart.gif        for (var i = 0; i < form.length; ++i) {
123InBlock.gif            var element = form.elements[i];
124ExpandedSubBlockStart.gif            if (element.name) {
125InBlock.gif                var elementValue = null;
126ExpandedSubBlockStart.gif                if (element.nodeName == "INPUT"{
127InBlock.gif                    var inputType = element.getAttribute("TYPE").toUpperCase();
128ExpandedSubBlockStart.gif                    if (inputType == "TEXT" || inputType == "PASSWORD" || inputType == "HIDDEN"{
129InBlock.gif                        elementValue = element.value;
130ExpandedSubBlockStart.gif                    }
 else if (inputType == "CHECKBOX" || inputType == "RADIO"{
131ExpandedSubBlockStart.gif                        if (element.checked{
132InBlock.gif                            elementValue = element.value;
133ExpandedSubBlockEnd.gif                        }

134ExpandedSubBlockEnd.gif                    }

135ExpandedSubBlockStart.gif                }
 else if (element.nodeName == "SELECT"{
136InBlock.gif                    elementValue = element.value;
137ExpandedSubBlockStart.gif                }
 else if (element.nodeName == "TEXTAREA"{
138InBlock.gif                    elementValue = element.value;
139ExpandedSubBlockEnd.gif                }

140ExpandedSubBlockStart.gif                if (elementValue) {
141InBlock.gif                    encodedData += "&" + element.name + "=" + encodeURIComponent(elementValue);
142ExpandedSubBlockEnd.gif                }

143ExpandedSubBlockEnd.gif            }

144ExpandedSubBlockEnd.gif        }

145ExpandedSubBlockEnd.gif    }

146InBlock.gif    //如果是调试,则弹出发送的数据。
147ExpandedSubBlockStart.gif    if (debugRequestText) {
148InBlock.gif        alert(encodedData);
149ExpandedSubBlockEnd.gif    }

150InBlock.gif    x.send(encodedData);//向服务器发送数据。
151ExpandedSubBlockStart.gif    if (!clientCallBack) {
152ExpandedSubBlockStart.gif        if (debugResponseText) {
153InBlock.gif            alert(x.responseText);
154ExpandedSubBlockEnd.gif        }

155InBlock.gif        result = eval("(" + x.responseText + ")");
156ExpandedSubBlockStart.gif        if (debugErrors && result.error) {
157InBlock.gif            alert("error: " + result.error);
158ExpandedSubBlockEnd.gif        }

159ExpandedSubBlockEnd.gif    }

160InBlock.gif    delete x;
161InBlock.gif    return result;
162ExpandedBlockEnd.gif}

163 None.gif
164 None.gif // Ajax End

  其他的不用多说明了,看注释应该就差不多了,如果有不对的地方请批评指教,谢谢!

本文转自网魂小兵博客园博客,原文链接:http://www.cnblogs.com/xdotnet/archive/2006/12/11/communityserver_xmlhttp_ajax.html,如需转载请自行联系原作者

相关文章
|
6月前
|
JSON 前端开发 JavaScript
JavaWeb14(ajax02判断账号是否存在&JSON介绍&AJAX+JSON字符串和对象之间的转换&JSON实现自动补全)
JavaWeb14(ajax02判断账号是否存在&JSON介绍&AJAX+JSON字符串和对象之间的转换&JSON实现自动补全)
|
1月前
|
XML 前端开发 JavaScript
AJAX - 创建 XMLHttpRequest 对象
AJAX - 创建 XMLHttpRequest 对象
|
2月前
|
XML 前端开发 JavaScript
AJAX - 创建 XMLHttpRequest 对象
AJAX - 创建 XMLHttpRequest 对象
|
3月前
|
XML JSON 前端开发
AJAX 中创建 XMLHttpRequest 对象的方法和常用属性、方法
AJAX 中创建 XMLHttpRequest 对象的方法和常用属性、方法
38 0
|
9月前
|
XML 前端开发 JavaScript
AJAX - 创建 XMLHttpRequest 对象
AJAX(异步JavaScript和XML)是一种在Web应用程序中创建快速动态更新的技术。使用AJAX,Web应用程序可以异步地向服务器发送和接收数据,而无需刷新整个页面。 AJAX广泛用于Web应用程序中,包括社交媒体,电子商务,在线游戏等等。 XMLHttpRequest 是AJAX中最重要的对象。它可以向服务器发送请求并接收响应。
|
Web App开发 JavaScript 应用服务中间件
第105天:Ajax 客户端与服务器基本知识
一、服务器 前言:通俗的讲,能够提供某种服务的机器(计算机)称为服务器 1、服务器类型 - 按服务类型可分为:文件服务器、数据库服务器、邮件服务器、Web服务器等 - 按操作系统可分为:Linux服务器、Windows服务器等 - 按应用软件可分为:Apache服务器、Nginx 服务器、IIS服务器、Tomcat服务器、 weblogic服务器、WebSphere服务器、boss服务器、 Node服务器等 2、 服务器软件     使计算机具备提供某种服务能力的应用软件,称为服务器软件, 通过安装相应的服务软件,然后进行配置后就可以使计算具备了提供某种服务的能力。
1234 0
|
5月前
|
XML 前端开发 JavaScript
什么是Ajax和jquery
什么是Ajax和jquery
38 0
|
4月前
|
JSON 前端开发 Java
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
57 0
|
4月前
|
敏捷开发 JavaScript 前端开发
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤
|
3月前
|
前端开发 JavaScript
Jquery ajax捕获错误信息
Jquery ajax捕获错误信息
16 0