前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >不懂JQuery的孩子:自封装Ajax函数

不懂JQuery的孩子:自封装Ajax函数

作者头像
^_^肥仔John
发布2018-01-18 11:24:26
1.4K0
发布2018-01-18 11:24:26
举报

前言                                    

  一直没痛下决心学习JQuery,但平时项目中又要用到Ajax,于是自己写一个函数封装一下方便项目中偷懒吧!今天一不小心看到介绍xmlHttp对象的博客,细读一下重新认识了一下xmlHttp对象,获益良多,顺便重构一下自己写的Ajax函数。

  主要参考:轻松掌握XMLHttpRequest对象

XMLHTTP.readyState的五种状态

认识XmlHttp对象                            

  XmlHttp:提供客户端与http服务器通信的协议。对于IE浏览器通过window.ActiveXObject()获取,其他浏览器用window.XMLHttpRequest()获取。

XmlHttp对象的属性:

XmlHttp对象的方法:

其中readyState有0,1,2,3,4这五个值

0:实例化了xmlHttp对象,还没调用xmlHttp对象的open方法;

1:调用xmlHttp对象的open方法,但还没调用send方法;

2:调用send方法后,服务器返回响应头,这时可以通过xmlHttp.getResponseHeader()来获取响应头;

3:服务器返回部分响应内容,这时可以xmlHttp.responseText有值,但只是部分内容而已,不能保证数据完整;

4:服务器处理完毕,这时xmlHttp.responseText的值为完整的响应内容,数据完整。

注意:

  1.上面的readyState不是每种浏览器都俱全。

  2. 因asp.net默认启动了输出缓存,如果不手动加上Response.Flush()的话,那么最后响应完成后2、3、4状态会一连串地变换。

具体实现                                

代码:

XmlHttpManagerHasPool.js

代码语言:javascript
复制
  1 function XmlHttpManagerHasPool()
  2 { 
  3 /*私有方法Start*/  
  4     var CreateXmlHttp = function(){
  5         if(window.XMLHttpRequest)
  6         { 
  7            return new XMLHttpRequest(); //非ie浏览器
  8         }
  9         else if(window.ActiveXObject)
 10         { 
 11            return new ActiveXObject("Microsoft.XMLHTTP"); //ie浏览器
 12         } 
 13         else
 14         { 
 15           return null;
 16         } 
 17     }
 18     
 19     var xmlHttpPool = null;
 20     var initXmlHttpCount = 3;//默认对象池中xmlHttp对象个数
 21     var Init_Pool = function(){
 22         xmlHttpPool = new Array();
 23         var tempXmlHttp = null;
 24         for(var i=initXmlHttpCount-1; i>=0; --i)
 25         {
 26             tempXmlHttp = CreateXmlHttp();
 27             if(tempXmlHttp)
 28                 xmlHttpPool.push(tempXmlHttp);
 29         }
 30     }
 31 /*私有方法End*/ 
 32 
 33 /*公开方法和事件Start*/
 34 
 35     //下面是一系列事件
 36     var OnNoXmlHttp = null;//当无法获取xmlHttp对象时触发,仅接受方法
 37     this.SetOnNoXmlHttp = function(method){
 38         if(typeof method=="function")
 39             OnNoXmlHttp = method;
 40     }
 41     var OnOpen = null;//当xmlHttp对象调用open方法后触发,仅接受方法。readyState由0变为1
 42     this.SetOnOpen = function(method){
 43         if(typeof method=="function")
 44             OnOpen = method;
 45     }
 46     var OnPreLoad = null;//当xmlHttp对象调用send方法,服务器发送响应头信息后触发,仅接受方法。readyState由1变为2
 47     this.SetOnPreLoad = function(method){
 48          if(typeof method=="function")
 49             OnPreLoad = method;
 50     }
 51     var OnLoading = null;//服务器发送部分响应内容后触发,readyState由2变为3,仅接受方法
 52     this.SetOnLoading = function(method){
 53           if(typeof method=="function")
 54                 OnLoading = method;
 55     }
 56     //当status不为200时触发,有默认处理函数,仅接受方法
 57     var OnError = function(xmlHttp){
 58         alert("Request is fail. Http Status Code:"+xmlHttp.status);
 59     }
 60     this.SetOnError = function(method){
 61           if(typeof method=="function")
 62                 OnError = method;
 63     }
 64     
 65     //初始化xmlHttp对象池
 66     this.InitPool = function(){
 67         Init_Pool();
 68     }
 69     
 70     //参数:postPar——当请求方式为POST时,所要传递的参数
 71     //      url——异步处理程序url
 72     //      method——请求方式:GET/POST
 73     //      onLoadComplete——请求成功后的结果处理程序,该处理程序需要两个参数:第一个参数为XMLHttpRequest对象,第二个参数为触发事件的对象(可选)
 74     //      argData——附件参数(可选),若要传多个值,可以用数组或map对象
 75     this.Startup = function(postPar,url,method,onLoadComplete,argData){
 76         //获取xmlHttp对象
 77         if(xmlHttpPool==null)
 78         {
 79             Init_Pool();
 80         }
 81 
 82         var xmlHttp = null;
 83         if(xmlHttpPool.length>=1)
 84         {
 85             xmlHttp = xmlHttpPool.shift();
 86         }
 87         else
 88         {
 89            xmlHttp = CreateXmlHttp();
 90         }
 91         if(xmlHttp==null)
 92         {
 93             if(OnNoXmlHttp)
 94                 OnNoXmlHttp();
 95             return false;
 96         }
 97         
 98         //成功获取
 99         var argumentLength = arguments.length;
100         xmlHttp.onreadystatechange  = function(){
101             switch(xmlHttp.readyState)
102             {
103                 case 1:
104                     if(OnOpen)
105                         OnOpen();
106                     break;
107                 case 2:
108                     if(OnPreLoad)
110                         OnPreLoad();
112                     break;
113                 case 3:
114                     if(OnLoading)
115                         OnLoading();
116                     break;
117                 case 4:
118                      if(xmlHttp.status == 200 && xmlHttp.statusText == "OK" )
119                      {
120                         switch(argumentLength)
121                         {
122                             case 5:
123                                 if(onLoadComplete!=null)
124                                 {
125                                     onLoadComplete(xmlHttp,argData);
126                                 }
127                                 break;
128                             case 4:
129                                 if(onLoadComplete!=null)
130                                 {
131                                     onLoadComplete(xmlHttp);
132                                 }
133                                 break;
134                             default:
135                                 alert("The number of argument  is wrong!");
136                                 return;
137                         }
138                     }
139                     else  if(OnError){
140                         OnError(xmlHttp);
141                     }
142                     xmlHttp.abort();//将xmlHttp的readyState设为0
143                     xmlHttpPool.push(xmlHttp);//释放回对象池
144                     break;
145                  default:
146                     if(OnError)
147                     {
148                         OnError(xmlHttp);
149                         xmlHttp.abort();//将xmlHttp的readyState设为0
150                         xmlHttpPool.push(xmlHttp);//释放回对象池
151                     }
152                     break;      
153             }
154         }
155         
156         xmlHttp.open(method,url,true);
157         if(method.toLowerCase() == "get")
158         {
159             xmlHttp.send(null);
160         }
161         else
162         {
163             xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
164             xmlHttp.setRequestHeader("Content-length", postPar.length);
165             xmlHttp.setRequestHeader("Connection", "close");
166             xmlHttp.send(postPar);
167         }
168     }
169 /*公开方法和事件End*/
170 }

使用实例——进度条:

aspx文件

代码语言:javascript
复制
 1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FlushTest.aspx.cs" Inherits="Client.FlushTest" %>
 2 
 3 <input type="button" id="btn" value="Click" onclick="Click()" />
 4 <br />
 5 <div style="height:20px;width:100px;overflow:hidden;border:solid 1px black">
 6     <div id="divProcess" style="height:20px;width:0px;background-color:Green"></div>
 7 </div>
 8 <div id="divText" style="width:100px">0%</div>
 9 <script src="XmlHttpManagerHasPool.js" type="text/javascript"></script>
10 <script type="text/javascript">
11 var dp = document.getElementById("divProcess");
12 var dt = document.getElementById("divText");
13 var xhp = new XmlHttpManagerHasPool();
14 xhp.SetOnNoXmlHttp(function(){alert("noxmlhttp");});
15 function onopen(){
16     dp.style.width = "25px";
17     dt.innerHTML = "25%";
18 }
19 xhp.SetOnOpen(onopen);
20 function onpreload(){
21     dp.style.width = "50px";
22     dt.innerHTML = "50%";
23 }
24 xhp.SetOnPreLoad(onpreload);
25 function onloading(){
26     dp.style.width = "75px";
27     dt.innerHTML = "75%";
28 }
29 xhp.SetOnLoading(onloading);
30 
31 function onloadc(){
32     dp.style.width = "100px";
33     dt.innerHTML = "100%";
34 }
35 function Click(){
36 xhp.Startup(null,"Handler1.ashx","get",onloadc);
37 }
38 </script>

aspx.cs文件

代码语言:javascript
复制
 1    public class Handler1 : IHttpHandler
 2     {
 3 
 4         public void ProcessRequest(HttpContext context)
 5         {
 6             context.Response.ContentType = "text/plain";
 7             Thread.Sleep(5000);
 8             context.Response.Flush();//发送响应头,readyState由1变为2
 9             Thread.Sleep(5000);
10             context.Response.Write("Hello World");
11             context.Response.Flush();//发送部分响应内容,readyState由2变3
12             Thread.Sleep(5000);
13             context.Response.Write("Hello World");
14             //响应内容发送完毕,readyState由3变4
15         }
16 
17         public bool IsReusable
18         {
19             get
20             {
21                 return false;
22             }
23         }
24     }

Ajax封装包基本写好了,不过对于JavaScript依然有很多不清楚的地方,要好好学一下才行。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2012-02-10 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档