Jquery使用ajax参数详解,异步HTTP请求操作

By admin in 4858.com on 2019年4月8日

一、说明

一、说明

【原创-算法-达成】异步HTTP请求操作,算法异步

一、说明

  1) 这么些类 是自己 在真正项目中,优消除决真正难题时,不参照第2方代码,完全由友好查阅MSDN官方文书档案 ,
完毕的三个实际生产条件中应用的效率类

  2) 读者在动用此类时,请尊重原创,在代码中添加原创注释://  Author —
Meng.NET (cnblogs.com)  ,同时欢迎 3次革新、叁回作文 以共同进步

  三)
此代码以【面向对象】、【C#闭包】、【异步回调】、【超时】、【等待】、【自动重试】格局贯彻及完结,且能够配备扩大

二、代码

  废话不多说,上干货,代码如下:

4858.com 1 1 ///
<summary> 2 /// 异步 Http 3 /// </summary> 4 public class
Remoter 5 { 6 /* 7 * LM,2016/08/18 8 * C#闭包化,异步化,Web操作 9 *
以便支持POS多接口多操作同时选择 10 */ 1一 1贰 /// <summary> 1叁 ///
请求地址 14 /// </summary> 壹伍 public string U本田UR-VL { get; set; } 1六一7 /// <summary> 1八 /// 请求方式 1玖 /// </summary> 20 public
string RequestMethod { get; set; } 贰一 22 /// <summary> 二三 ///
伸手数据 二四 /// </summary> 贰五 public string JsonContent { get;
set; } 二陆 二柒 // 2八 private byte[] Buffer { get; set; } 29 private
Stream RequestStream { get; set; } 30 private HttpWebRequest Request {
get; set; } 31 private bool ResponseFlag { get; set; } 32 private string
Result { get; set; } 33 private bool TimeoutFlag { get; set; } 34
private int TimeoutTime { get; set; } 35 private bool RetryFlag { get;
set; } 36 private int RetryCount { get; set; } 37 private int WaitSleep
{ get; set; } 38 private int TrySleep { get; set; } 39 40 // 初始化 41
public Remoter() 42 { 43 // 44 ServicePointManager.SecurityProtocol =
SecurityProtocolType.Tls | SecurityProtocolType.Ssl3; 45
ServicePointManager.ServerCertificateValidationCallback = new
RemoteCertificateValidationCallback((object sender, X509Certificate
certificate, X509Chain chain, SslPolicyErrors errors) => true); 46 47
// 48 this.URL = string.Empty; 49 this.Request =
default(HttpWebRequest); 50 this.JsonContent = string.Empty; 51
this.Buffer = default(byte[]); 52 this.RequestStream =
default(Stream); 53 this.ResponseFlag = false; 54 this.Result =
string.Empty; 55 this.TimeoutFlag = false; 56 this.TimeoutTime = 10 *
1000; 5柒 this.RetryFlag = false; 5捌 this.RetryCount = 3; 5九this.WaitSleep = 拾; 60 this.RequestMethod = “POST”; 陆一 this.TrySleep =
贰仟; 6二 } 6三 6四 /// <summary> 陆五 /// 获取响应数据 6陆 ///
</summary> 陆7 public string GetRemoteData() 68 { 6九 // 70
if(string.IsNullOr惠特eSpace(this.U翼虎L)) 7一 { 72 throw new
Exception(“HttpAsync.U大切诺基L,未赋值!”); 7三 } 7四 75 // 76RemoteNew(SetResult); 77 7八 // 7九 var timeNum = 0; 80 while (true) 81 {
八二 if (ResponseFlag) 八三 { 84 break; 8伍 } 8陆 if (提姆eoutFlag) 八七 { 8八throw new Exception(string.Format(“请求超时!超时时间:{0}S”, TimeoutTime
/ 一千)); 8九 } 90 timeNum += WaitSleep; 玖一 if (timeNum >=
TimeoutTime) 9二 { 九三 TimeoutFlag = true; 九四 } 95Thread.Sleep(WaitSleep); 玖陆 } 九柒 玖8 // 9九 return Result; 100 } 十壹 十2
// 十三 private void RemoteNew(Action<Remoter, string> action) 10四{ 105 // ⑩陆 var reNum = 0; 107 for (var i = 0; i < this.RetryCount;
i++) 拾捌 { 十九 try 1拾 { 11壹 // 112 var uri = ULANDL; 1壹3 114 // 115this.Request = WebRequest.Create(uri) as HttpWebRequest; 116this.Request.KeepAlive = false; 117 this.Request.Method =
this.RequestMethod; 11八 this.Request.Credentials =
CredentialCache.DefaultCredentials; 11九 if
(this.RequestMethod.Equals(“POST”, StringComparison.OrdinalIgnoreCase))
120 { 12壹 this.Buffer = Encoding.UTF八.GetBytes(this.JsonContent); 12贰this.Request.ContentLength = this.Buffer.Length; 1二三this.Request.ContentType = “application/json”; 1贰四 this.RequestStream =
this.Request.GetRequestStream(); 125this.RequestStream.Write(this.Buffer, 0, this.Buffer.Length); 12陆this.RequestStream.Close(); 1二柒 } 12八 12玖 // 130
this.Request.BeginGetResponse((arr) => 13一 { 13二 // 13三 var state =
arr.AsyncState as Remoter; 134 // 13伍 var response =
state.Request.EndGetResponse(arr) as HttpWebResponse; 13陆 var respStream
= new StreamReader(response.GetResponseStream(),
Encoding.GetEncoding(“UTF-八”)); 1三七 action(state,
respStream.ReadToEnd()); 13八 respStream.Close(); 13玖 response.Close();
140 }, this); 1四一 // 14二 break; 1肆③ } 14肆 catch (Exception ex) 145 { 1肆6Thread.Sleep(this.TrySleep); 1四七 reNum++; 14八 if (reNum ==
this.RetryCount) 149 { 150 throw new
Exception(string.Format(“重试失利!重试次数:{0}次,失败原因:{1}”,
this.RetryCount, ex.Message)); 15一 } 15二 continue; 一伍3 } 15四 } 155 } 156private void SetResult(Remoter state, string jsonData) 一伍柒 { 158 if
(!string.IsNullOrWhiteSpace(jsonData)) 159 { 160 state.Result =
jsonData; 161 state.ResponseFlag = true; 162 } 163 } 164 } Remoter.cs

  使用办法:

  GET: 

4858.com 21 var
remoter = new Remoter(); 贰 remoter.RequestMethod = “GET”; 叁 remoter.U猎豹CS六L
= “那里是你要请求的U奇骏L”; 四 var response = remoter.GetRemoteData(); View Code

  POST:

4858.com 3一 var
remoter = new Remoter(); 贰 remoter.RequestMethod = “POST”; 三 remoter.U帕杰罗L
= “你要央浼的U索罗德L”; 四 remoter.JsonContent = “你要想U奥迪Q5L发送的JSON数据”; 5var response = remoter.GetRemoteData(); View Code

3、代码解析

    public Remoter() 开头化本类,可配备到 App.config/Web.config 中

4858.com 4 1 // 2
this.URL = string.Empty; 3 this.Request = default(HttpWebRequest); 4
this.JsonContent = string.Empty; 5 this.Buffer = default(byte[]Jquery使用ajax参数详解,异步HTTP请求操作。); 6
this.RequestStream = default(Stream); 7 this.ResponseFlag = false; 8
this.Result = string.Empty; 9 this.TimeoutFlag = false; 10
this.TimeoutTime = 10 * 一千; 1一 this.RetryFlag = false; 12this.RetryCount = 三; 1三 this.WaitSleep = 十; 14 this.RequestMethod =
“POST”; 15 this.TrySleep = 两千; 可从安顿文件读取部分

  public string U奥迪Q5L 要呼吁的地点

  public string RequestMethod HTTP 动词

  public string JsonContent POST 请求时,发送的json数据

  private byte[] Buffer 设置请求流的byte数组

  private Stream RequestStream 请求流

  private HttpWebRequest Request HTTP请求对象

  private bool ResponseFlag 与请求对应的响应是或不是中标标识

  private string Result 回调状态保持对象,保存响应结果用

  private bool TimeoutFlag 总超时时间是还是不是过期标识

  private int TimeoutTime 总超时时间(包括若干次重试),暗中认可拾s

  private int RetryCount 总U中华VL调用(失败)自动重试次数,暗中同意叁次

  private int WaitSleep 主线程,仿Ajax回调等待时间,暗许十ms

  private int TrySleep 每一趟请求地址战败后,重试时间间隔,默许贰s

  public string GetRemoteData()  解析:

4858.com 5 一 // 二var timeNum = 0; 三 while (true) 4 { 5 if (ResponseFlag) 六 { 7 break; 捌 }
玖 if (TimeoutFlag) 10 { 11 throw new
Exception(string.Format(“请求超时!超时时间:{0}S”, TimeoutTime / 一千));
1二 } 13 timeNum += WaitSleep; 14 if (timeNum >= 提姆eoutTime) 一伍 { 16TimeoutFlag = true; 一七 } 1八 Thread.Sleep(WaitSleep); 1九 } 主线程,仿Ajax回调等待

  private void RemoteNew(Action<Remoter, string> action) 解析:

4858.com 6 壹 private
void RemoteNew(Action<Remoter, string> action) 二 { 3 // 四 var
reNum = 0; 5 for (var i = 0; i < this.RetryCount; i++) 六 { 七 try 八 {
九 // 此处省略 10 //… … 1一 1贰 // 一3 break; 1四 } 15 catch (Exception
ex) 1六 { 一七 Thread.Sleep(this.TrySleep); 1八 reNum++; 1九 if (reNum ==
this.RetryCount) 20 { 2一 throw new
Exception(string.Format(“重试失利!重试次数:{0}次,失败原因:{1}”,
this.RetryCount, ex.Message)); 2二 } 二三 continue; 2肆 } 25 } 2陆 } 调用U途锐L失利,自动重试机制
4858.com 7 一 // 贰this.Request.BeginGetResponse((arr) => 3 { 肆 // 五 var state =
arr.AsyncState as Remoter; 陆 // 七 var response =
state.Request.EndGetResponse(arr) as HttpWebResponse; 八 var respStream =
new StreamReader(response.GetResponseStream(),
Encoding.GetEncoding(“UTF-捌”)); 九 action(state, respStream.ReadToEnd());
拾 respStream.Close(); 1一 response.Close(); 1二 }, this); 异步响应回调,闭包与自状态保持

   private void SetResult(Remoter state, string jsonData) 解析:

4858.com 81state.Result = jsonData; 二 state.ResponseFlag = true; 异步响应成功后,在情景保持中赋值结果

4、安插中的开源项目…

  
 安排一连会将生育中解决难题的好多地点汇集成三个档次【Meng.Net.dll】并开源至GitHub上,欢迎沟通,共同提升~~

  至于本文所讲的类会在哪些命名空间中,还没想好,项指标欧洲经济共同体布局及主打方向,敬请期待……

 

                                         蒙

                                    2016-09-24
 22:37  周六

 

 

 

            
支付宝打赏:                                   
微信打赏:  

      
4858.com 9              
4858.com 10

 

1、表达 一) 这些类 是本人 在真实项目中,优消除决真正问题时,不参照第壹方代码,完全…

笔录一下  Jquery使用ajax(post.get及参数详解)

  1) 那些类 是自小编 在实际项目中,优化解决实际问题时,不参照第叁方代码,完全由本身查阅MSDN官方文书档案 ,
落成的3个实际生产环境中使用的功能类

  1) 这几个类 是本身 在真正项目中,优化解决真正问题时,不参照第一方代码,完全由友好查阅MSDN官方文档 ,
完毕的五个实际生产条件中应用的效用类

1、get:

  二) 读者在动用此类时,请尊重原创,在代码中添加原创注释://  Author —
Meng.NET (cnblogs.com)  ,同时欢迎 三次改良、二回作文 以共同进步

  二) 读者在行使此类时,请爱抚原创,在代码中加上原创注释://  Author —
Meng.NET (cnblogs.com)  ,同时欢迎 1回改善、一次创作 以共同提高

 1 $.ajax({
 2             type: "GET",
 3             url: baseUrl + "Showcontent/del_user?type=1&id=" + id + "&r=" + Math.random(),
 4             async: true,
 5             error: function () {
 6                 alert("Connection error");
 7             },
 8             success: function (data) {
 9                 $("#content").html(data); //data即为后台返回的数据
10             }
11         })

  三)
此代码以【面向对象】、【C#闭包】、【异步回调】、【超时】、【等待】、【自动重试】形式实现及实现,且能够安插扩张

  三)
此代码以【面向对象】、【C#闭包】、【异步回调】、【超时】、【等待】、【自动重试】格局达成及完成,且能够安插扩大

2.post:

二、代码

二、代码

$.ajax({
        type: "POST",
        url: baseUrl + "Showcontent/modify_user?r=" + Math.random(),
        async: true,
        data: $('#form_add').serialize(),//post参数
        error: function () {
            alert("Connection error");
        },
        success: function (data) {
            $("#content").html(data); //data即为后台返回的数据
        }
    })

  废话不多说,上干货,代码如下:

  废话不多说,上干货,代码如下:

 三、参数解释

4858.com 114858.com 12

4858.com 134858.com 14

(1)type: 请求格局,暗许为GET。壹般只用到“GET”,“POST”;类型:string

  1     /// <summary>
  2     /// 异步 Http
  3     /// </summary>
  4     public class Remoter
  5     {
  6         /*
  7          * LM,2016/08/18
  8          * C#闭包化,异步化,Web操作
  9          * 以便支持POS多接口多操作同时使用
 10          */
 11 
 12         /// <summary>
 13         /// 请求地址
 14         /// </summary>
 15         public string URL { get; set; }
 16 
 17         /// <summary>
 18         /// 请求方式
 19         /// </summary>
 20         public string RequestMethod { get; set; }
 21 
 22         /// <summary>
 23         /// 请求数据
 24         /// </summary>
 25         public string JsonContent { get; set; }
 26 
 27         //
 28         private byte[] Buffer { get; set; }        
 29         private Stream RequestStream { get; set; }        
 30         private HttpWebRequest Request { get; set; }        
 31         private bool ResponseFlag { get; set; }        
 32         private string Result { get; set; }        
 33         private bool TimeoutFlag  { get; set; }        
 34         private int TimeoutTime { get; set; }        
 35         private bool RetryFlag { get; set; }        
 36         private int RetryCount  { get; set; }        
 37         private int WaitSleep { get; set; }        
 38         private int TrySleep { get; set; }
 39 
 40         // 初始化
 41         public Remoter()
 42         {
 43             //
 44             ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
 45             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true);
 46 
 47             // 
 48             this.URL = string.Empty;
 49             this.Request = default(HttpWebRequest);
 50             this.JsonContent = string.Empty;
 51             this.Buffer = default(byte[]);
 52             this.RequestStream = default(Stream);
 53             this.ResponseFlag = false;
 54             this.Result = string.Empty;
 55             this.TimeoutFlag = false;
 56             this.TimeoutTime = 10 * 1000;
 57             this.RetryFlag = false;
 58             this.RetryCount = 3;
 59             this.WaitSleep = 10;
 60             this.RequestMethod = "POST";
 61             this.TrySleep = 2000;
 62         }
 63         
 64         /// <summary>
 65         /// 获取响应数据
 66         /// </summary>
 67         public string GetRemoteData()
 68         {
 69             //
 70             if(string.IsNullOrWhiteSpace(this.URL))
 71             {
 72                 throw new Exception("HttpAsync.URL,未赋值!");
 73             }
 74 
 75             // 
 76             RemoteNew(SetResult); 
 77 
 78             //
 79             var timeNum = 0;
 80             while (true)
 81             {
 82                 if (ResponseFlag)
 83                 {
 84                     break;
 85                 }
 86                 if (TimeoutFlag)
 87                 {
 88                     throw new Exception(string.Format("请求超时!超时时间:{0}S", TimeoutTime / 1000));
 89                 }
 90                 timeNum += WaitSleep;
 91                 if (timeNum >= TimeoutTime)
 92                 {
 93                     TimeoutFlag = true;
 94                 }
 95                 Thread.Sleep(WaitSleep);
 96             }
 97 
 98             //
 99             return Result;
100         }
101 
102         // 
103         private void RemoteNew(Action<Remoter, string> action) 
104         {
105             //
106             var reNum = 0;
107             for (var i = 0; i < this.RetryCount; i++)
108             {
109                 try
110                 {
111                     //
112                     var uri = URL;
113 
114                     //
115                     this.Request = WebRequest.Create(uri) as HttpWebRequest;
116                     this.Request.KeepAlive = false;
117                     this.Request.Method = this.RequestMethod;
118                     this.Request.Credentials = CredentialCache.DefaultCredentials;
119                     if (this.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
120                     {
121                         this.Buffer = Encoding.UTF8.GetBytes(this.JsonContent);
122                         this.Request.ContentLength = this.Buffer.Length;
123                         this.Request.ContentType = "application/json";
124                         this.RequestStream = this.Request.GetRequestStream();
125                         this.RequestStream.Write(this.Buffer, 0, this.Buffer.Length);
126                         this.RequestStream.Close();
127                     }
128 
129                     //
130                     this.Request.BeginGetResponse((arr) =>
131                     {
132                         //
133                         var state = arr.AsyncState as Remoter;
134                         //
135                         var response = state.Request.EndGetResponse(arr) as HttpWebResponse;
136                         var respStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
137                         action(state, respStream.ReadToEnd());
138                         respStream.Close();
139                         response.Close();
140                     }, this);
141                     //
142                     break;
143                 }
144                 catch (Exception ex)
145                 {
146                     Thread.Sleep(this.TrySleep);
147                     reNum++;
148                     if (reNum == this.RetryCount)
149                     {
150                         throw new Exception(string.Format("重试失败!重试次数:{0}次,失败原因:{1}", this.RetryCount, ex.Message));
151                     }
152                     continue;
153                 }
154             }
155         }        
156         private void SetResult(Remoter state, string jsonData)
157         {
158             if (!string.IsNullOrWhiteSpace(jsonData))
159             {
160                 state.Result = jsonData;
161                 state.ResponseFlag = true;
162             }
163         }
164     }
  1     /// <summary>
  2     /// 异步 Http
  3     /// </summary>
  4     public class Remoter
  5     {
  6         /*
  7          * LM,2016/08/18
  8          * C#闭包化,异步化,Web操作
  9          * 以便支持POS多接口多操作同时使用
 10          */
 11 
 12         /// <summary>
 13         /// 请求地址
 14         /// </summary>
 15         public string URL { get; set; }
 16 
 17         /// <summary>
 18         /// 请求方式
 19         /// </summary>
 20         public string RequestMethod { get; set; }
 21 
 22         /// <summary>
 23         /// 请求数据
 24         /// </summary>
 25         public string JsonContent { get; set; }
 26 
 27         //
 28         private byte[] Buffer { get; set; }        
 29         private Stream RequestStream { get; set; }        
 30         private HttpWebRequest Request { get; set; }        
 31         private bool ResponseFlag { get; set; }        
 32         private string Result { get; set; }        
 33         private bool TimeoutFlag  { get; set; }        
 34         private int TimeoutTime { get; set; }        
 35         private bool RetryFlag { get; set; }        
 36         private int RetryCount  { get; set; }        
 37         private int WaitSleep { get; set; }        
 38         private int TrySleep { get; set; }
 39 
 40         // 初始化
 41         public Remoter()
 42         {
 43             //
 44             ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Ssl3;
 45             ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback((object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) => true);
 46 
 47             // 
 48             this.URL = string.Empty;
 49             this.Request = default(HttpWebRequest);
 50             this.JsonContent = string.Empty;
 51             this.Buffer = default(byte[]);
 52             this.RequestStream = default(Stream);
 53             this.ResponseFlag = false;
 54             this.Result = string.Empty;
 55             this.TimeoutFlag = false;
 56             this.TimeoutTime = 10 * 1000;
 57             this.RetryFlag = false;
 58             this.RetryCount = 3;
 59             this.WaitSleep = 10;
 60             this.RequestMethod = "POST";
 61             this.TrySleep = 2000;
 62         }
 63         
 64         /// <summary>
 65         /// 获取响应数据
 66         /// </summary>
 67         public string GetRemoteData()
 68         {
 69             //
 70             if(string.IsNullOrWhiteSpace(this.URL))
 71             {
 72                 throw new Exception("HttpAsync.URL,未赋值!");
 73             }
 74 
 75             // 
 76             RemoteNew(SetResult); 
 77 
 78             //
 79             var timeNum = 0;
 80             while (true)
 81             {
 82                 if (ResponseFlag)
 83                 {
 84                     break;
 85                 }
 86                 if (TimeoutFlag)
 87                 {
 88                     throw new Exception(string.Format("请求超时!超时时间:{0}S", TimeoutTime / 1000));
 89                 }
 90                 timeNum += WaitSleep;
 91                 if (timeNum >= TimeoutTime)
 92                 {
 93                     TimeoutFlag = true;
 94                 }
 95                 Thread.Sleep(WaitSleep);
 96             }
 97 
 98             //
 99             return Result;
100         }
101 
102         // 
103         private void RemoteNew(Action<Remoter, string> action) 
104         {
105             //
106             var reNum = 0;
107             for (var i = 0; i < this.RetryCount; i++)
108             {
109                 try
110                 {
111                     //
112                     var uri = URL;
113 
114                     //
115                     this.Request = WebRequest.Create(uri) as HttpWebRequest;
116                     this.Request.KeepAlive = false;
117                     this.Request.Method = this.RequestMethod;
118                     this.Request.Credentials = CredentialCache.DefaultCredentials;
119                     if (this.RequestMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
120                     {
121                         this.Buffer = Encoding.UTF8.GetBytes(this.JsonContent);
122                         this.Request.ContentLength = this.Buffer.Length;
123                         this.Request.ContentType = "application/json";
124                         this.RequestStream = this.Request.GetRequestStream();
125                         this.RequestStream.Write(this.Buffer, 0, this.Buffer.Length);
126                         this.RequestStream.Close();
127                     }
128 
129                     //
130                     this.Request.BeginGetResponse((arr) =>
131                     {
132                         //
133                         var state = arr.AsyncState as Remoter;
134                         //
135                         var response = state.Request.EndGetResponse(arr) as HttpWebResponse;
136                         var respStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
137                         action(state, respStream.ReadToEnd());
138                         respStream.Close();
139                         response.Close();
140                     }, this);
141                     //
142                     break;
143                 }
144                 catch (Exception ex)
145                 {
146                     Thread.Sleep(this.TrySleep);
147                     reNum++;
148                     if (reNum == this.RetryCount)
149                     {
150                         throw new Exception(string.Format("重试失败!重试次数:{0}次,失败原因:{1}", this.RetryCount, ex.Message));
151                     }
152                     continue;
153                 }
154             }
155         }        
156         private void SetResult(Remoter state, string jsonData)
157         {
158             if (!string.IsNullOrWhiteSpace(jsonData))
159             {
160                 state.Result = jsonData;
161                 state.ResponseFlag = true;
162             }
163         }
164     }

(贰)url:请求的地方;类型:string

Remoter.cs

Remoter.cs

(三)async:私下认可true,true-请求为异步请求,false-请求为共同请求(同步请求将锁住浏览器,用户别的操作必须等 待请求完毕才足以执行);类型:bool

  使用方式:

  使用办法:

(4)timeout: 设置请求超时时间(皮秒);类型:int

  GET: 

  GET: 

(5)cache:暗中认可为true(当dataType为script时,暗许为false); 设置为false将不会从浏览器缓存中加载请求音信;类型:bool

4858.com 154858.com 16

4858.com 174858.com 18

(6)data: 发送到服务器的数据(例:a:”a”,b:”b” 
$(‘#formid’).serialize()自动转换form表单);类型:string

1 var remoter = new Remoter();
2 remoter.RequestMethod = "GET";
3 remoter.URL = "这里是你要请求的URL";
4 var response = remoter.GetRemoteData();
1 var remoter = new Remoter();
2 remoter.RequestMethod = "GET";
3 remoter.URL = "这里是你要请求的URL";
4 var response = remoter.GetRemoteData();

(7)dataType:
预期服务器重临的数据类型。若是不钦点,JQuery将机关依照http包mime新闻重返responseXML或responseText,并作为回调函数参数字传送递。);类型:string

View Code

View Code

          可用的项目如下:

  POST:

  POST:

          xml:返回XML文档,可用JQuery处理。

4858.com 194858.com 20

4858.com 214858.com 22

          html:再次回到纯文本HTML消息;包蕴的script标签会在插入DOM时实施。

1 var remoter = new Remoter();
2 remoter.RequestMethod = "POST";
3 remoter.URL = "你要请求的URL";
4 remoter.JsonContent = "你要想URL发送的JSON数据";
5 var response = remoter.GetRemoteData();
1 var remoter = new Remoter();
2 remoter.RequestMethod = "POST";
3 remoter.URL = "你要请求的URL";
4 remoter.JsonContent = "你要想URL发送的JSON数据";
5 var response = remoter.GetRemoteData();

         
script:再次回到纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在中距离请求

View Code

View Code

                  时(不在同四个域下),全体post请求都将转为get请求。

三、代码解析

叁、代码解析

          json:返回JSON数据。

    public Remoter()
伊始化本类,可配备到 App.config/Web.config 中

    public Remoter()
开首化本类,可配置到 App.config/Web.config 中

         
jsonp:JSONP格式。使用SONP格局调用函数时,例如myurl?callback=?,JQuery将活动替换后2个

4858.com 234858.com 24

4858.com 254858.com 26

                “?”为科学的函数名,以履行回调函数。

 1             // 
 2             this.URL = string.Empty;
 3             this.Request = default(HttpWebRequest);
 4             this.JsonContent = string.Empty;
 5             this.Buffer = default(byte[]);
 6             this.RequestStream = default(Stream);
 7             this.ResponseFlag = false;
 8             this.Result = string.Empty;
 9             this.TimeoutFlag = false;
10             this.TimeoutTime = 10 * 1000;
11             this.RetryFlag = false;
12             this.RetryCount = 3;
13             this.WaitSleep = 10;
14             this.RequestMethod = "POST";
15             this.TrySleep = 2000;
 1             // 
 2             this.URL = string.Empty;
 3             this.Request = default(HttpWebRequest);
 4             this.JsonContent = string.Empty;
 5             this.Buffer = default(byte[]);
 6             this.RequestStream = default(Stream);
 7             this.ResponseFlag = false;
 8             this.Result = string.Empty;
 9             this.TimeoutFlag = false;
10             this.TimeoutTime = 10 * 1000;
11             this.RetryFlag = false;
12             this.RetryCount = 3;
13             this.WaitSleep = 10;
14             this.RequestMethod = "POST";
15             this.TrySleep = 2000;

          text:重返纯文本字符串。

可从安插文件读取部分

可从配置文件读取部分

(八)beforeSend:发送请求前能够修改XMLHttpRequest对象的函数,例如添加自定义HTTP头。在beforeSend中壹经回到false可以废除这一次ajax请求。XMLHttpRequest对象是惟一的参数。

  public string UOdysseyL
要呼吁的地点

  public string U本田CR-VL
要伏乞的地址

            function(XMLHttpRequest){

  public string
RequestMethod HTTP 动词

  public string
RequestMethod HTTP 动词

               this;   //调用此次ajax请求时传递的options参数

  public string
JsonContent POST 请求时,发送的json数据

  public string
JsonContent POST 请求时,发送的json数据

            }

  private byte[]
Buffer 设置请求流的byte数组

  private byte[]
Buffer 设置请求流的byte数组

(九)complete:请求完毕后调用的回调函数(请求成功或破产时均调用)。参数:XMLHttpRequest对象和1个描述成功请求类型的字符串。

  private Stream
RequestStream 请求流

  private Stream
RequestStream 请求流

          function(XMLHttpRequest, textStatus){

  private HttpWebRequest
Request HTTP请求对象

  private HttpWebRequest
Request HTTP请求对象

             this;    //调用此次ajax请求时传递的options参数

  private bool
ResponseFlag 与请求对应的响应是不是中标标识

  private bool
ResponseFlag 与请求对应的响应是不是成功标识

          }

  private string
Result 回调状态保持对象,保存响应结果用

  private string
Result 回调状态保持对象,保存响应结果用

(10)success:请求成功后调用的回调函数,有多少个参数。

  private bool
提姆eoutFlag 总超时时间是不是过期标识

  private bool
TimeoutFlag 总超时时间是还是不是过期标识

         1)由服务器再次回到,并依照dataType参数进行处理后的数据。

  private int
Timeout提姆e 总超时时间(包蕴若干次重试),默许10s

  private int
TimeoutTime 总超时时间(包罗若干次重试),暗许10s

         2)描述状态的字符串。

  private int
RetryCount 总U劲客L调用(失利)自动重试次数,暗中认可3遍

  private int
RetryCount 总UOdysseyL调用(战败)自动重试次数,私下认可3遍

         function(data, textStatus){

  private int
WaitSleep 主线程,仿Ajax回调等待时间,私下认可10ms

  private int
WaitSleep 主线程,仿Ajax回调等待时间,暗中同意拾ms

            //data可能是xmlDoc、jsonObj、html、text等等

  private int TrySleep
每趟请求地址战败后,重试时间距离,暗中同意二s

  private int TrySleep
每趟请求地址战败后,重试时间间隔,私下认可2s

            this;  //调用本次ajax请求时传递的options参数

  public string
GetRemoteData()  解析:

  public string
GetRemoteData()  解析:

4858.com,(1贰)error:请求失利时被调用的函数。该函数有2个参数,即XMLHttpRequest对象、错误音信、捕获的荒谬对象(可选)。

4858.com 274858.com 28

4858.com 294858.com 30

       ajax事件函数如下:

 1             //
 2             var timeNum = 0;
 3             while (true)
 4             {
 5                 if (ResponseFlag)
 6                 {
 7                     break;
 8                 }
 9                 if (TimeoutFlag)
10                 {
11                     throw new Exception(string.Format("请求超时!超时时间:{0}S", TimeoutTime / 1000));
12                 }
13                 timeNum += WaitSleep;
14                 if (timeNum >= TimeoutTime)
15                 {
16                     TimeoutFlag = true;
17                 }
18                 Thread.Sleep(WaitSleep);
19             }
 1             //
 2             var timeNum = 0;
 3             while (true)
 4             {
 5                 if (ResponseFlag)
 6                 {
 7                     break;
 8                 }
 9                 if (TimeoutFlag)
10                 {
11                     throw new Exception(string.Format("请求超时!超时时间:{0}S", TimeoutTime / 1000));
12                 }
13                 timeNum += WaitSleep;
14                 if (timeNum >= TimeoutTime)
15                 {
16                     TimeoutFlag = true;
17                 }
18                 Thread.Sleep(WaitSleep);
19             }

       function(XMLHttpRequest, textStatus, errorThrown){

主线程,仿Ajax回调等待

主线程,仿Ajax回调等待

          //平日情况下textStatus和errorThrown只有个中二个暗含消息

  private void
RemoteNew(Action<Remoter, string> action) 解析:

  private void
RemoteNew(Action<Remoter, string> action) 解析:

          this;   //调用这一次ajax请求时传递的options参数

4858.com 314858.com 32

4858.com 334858.com 34

       }

 1         private void RemoteNew(Action<Remoter, string> action) 
 2         {
 3             //
 4             var reNum = 0;
 5             for (var i = 0; i < this.RetryCount; i++)
 6             {
 7                 try
 8                 {
 9                     // 此处省略
10                     //... ...
11 
12                     //
13                     break;
14                 }
15                 catch (Exception ex)
16                 {
17                     Thread.Sleep(this.TrySleep);
18                     reNum++;
19                     if (reNum == this.RetryCount)
20                     {
21                         throw new Exception(string.Format("重试失败!重试次数:{0}次,失败原因:{1}", this.RetryCount, ex.Message));
22                     }
23                     continue;
24                 }
25             }
26         }                        
 1         private void RemoteNew(Action<Remoter, string> action) 
 2         {
 3             //
 4             var reNum = 0;
 5             for (var i = 0; i < this.RetryCount; i++)
 6             {
 7                 try
 8                 {
 9                     // 此处省略
10                     //... ...
11 
12                     //
13                     break;
14                 }
15                 catch (Exception ex)
16                 {
17                     Thread.Sleep(this.TrySleep);
18                     reNum++;
19                     if (reNum == this.RetryCount)
20                     {
21                         throw new Exception(string.Format("重试失败!重试次数:{0}次,失败原因:{1}", this.RetryCount, ex.Message));
22                     }
23                     continue;
24                 }
25             }
26         }                        

(壹叁)contentType:当发送新闻至服务器时,内容编码类型暗中认可为”application/x-www-form-urlencoded”。该暗中认可值适合大部分运用地方;类型:string

调用U宝马X5L失利,自动重试机制

调用UMuranoL失利,自动重试机制

(1四)dataFilter:给Ajax再次来到的固有数据开展预处理的函数。

4858.com 354858.com 36

4858.com 374858.com 38

           
提供data和type五个参数。data是Ajax重临的原本数据,type是调用jQuery.ajax时提供的

 1                     //
 2                     this.Request.BeginGetResponse((arr) =>
 3                     {
 4                         //
 5                         var state = arr.AsyncState as Remoter;
 6                         //
 7                         var response = state.Request.EndGetResponse(arr) as HttpWebResponse;
 8                         var respStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
 9                         action(state, respStream.ReadToEnd());
10                         respStream.Close();
11                         response.Close();
12                     }, this);
 1                     //
 2                     this.Request.BeginGetResponse((arr) =>
 3                     {
 4                         //
 5                         var state = arr.AsyncState as Remoter;
 6                         //
 7                         var response = state.Request.EndGetResponse(arr) as HttpWebResponse;
 8                         var respStream = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
 9                         action(state, respStream.ReadToEnd());
10                         respStream.Close();
11                         response.Close();
12                     }, this);

            dataType参数。函数再次回到的值将由jQuery进一步处理。

异步响应回调,闭包与自状态保持

异步响应回调,闭包与自状态保持

            function(data, type){

   private void
SetResult(Remoter state, string jsonData) 解析:

   private void
SetResult(Remoter state, string jsonData) 解析:

                //再次回到处理后的数量

4858.com 394858.com 40

4858.com 414858.com 42

                return data;

1                 state.Result = jsonData;
2                 state.ResponseFlag = true;
1                 state.Result = jsonData;
2                 state.ResponseFlag = true;

            }

异步响应成功后,在情状保持中赋值结果

异步响应成功后,在场合保持中赋值结果

(一伍)global:默许为true。表示是或不是接触全局ajax事件。设置为false将不会接触全局ajax事件,ajaxStart或ajaxStop可用来控制各个ajax事件;类型:bool

四、安排中的开源项目…

肆、布署中的开源项目…

(16)ifModified:暗许为false。仅在服务器数据变动时取得新数据。 服务器数据变动判断的依据是Last-Modified头音信。暗许值是false,即忽略头信息;类型:bool

  
 布置继续会将生产中国化学工业进出口总集团解难点的不少地点集聚成四个门类【Meng.Net.dll】并开源至GitHub上,欢迎交换,共同进步~~

  
 安顿一连会将生产中解决难点的广大地点集聚成2个类型【Meng.Net.dll】并开源至GitHub上,欢迎沟通,共同提升~~

(一柒)jsonp:,在3个jsonp请求中重写回调函数的名字。 该值用来代表在”callback=?”那种GET或POST请求中UPAJEROL参数里的”callback”部分;类型:string

  至于本文所讲的类会在哪个命名空间中,还没想好,项目标完好布局及主打方向,敬请期待……

  至于本文所讲的类会在哪些命名空间中,还没想好,项指标完整结构及主打方向,敬请期待……

    例如:{jsonp:’onJsonPLoad’}会促成将”onJsonPLoad=?”传给服务器。

 

 

(1八)username:用于响应HTTP访问认证请求的用户名;类型:string

                                         蒙

                                         蒙

(1玖)password:用于响应HTTP访问认证请求的密码;类型:string

                                    2016-09-24
 22:37  周六

                                    2016-09-24
 22:37  周六

(20)processData:默许为true。私下认可情状下,发送的数额将被转移为指标(从技术角度来讲不用字符串)以合营暗许内容类型”application/x-www-form-urlencoded”;类型:bool

 

 

    若是要发送DOM树音信可能其它不期待转换的音讯,请设置为false。

 

 

(二一)scriptCharset:唯有当呼吁时dataType为”jsonp”或然”script”,并且type是GET时才会用于强制修改字符集(charset)。常常在地面和远程的剧情编码分歧时选用;类型:string

 

 

       

       

                    

                    

 

 

发表评论

电子邮件地址不会被公开。 必填项已用*标注

网站地图xml地图
Copyright @ 2010-2019 美高梅手机版4858 版权所有