原生ajax源码

 1 function GetXHR(){
 2             var xhr = null;
 3             if(XMLHttpRequest){
 4                 xhr = new XMLHttpRequest();        #如果没有XMLHttpRequest对象就使用ie的ActiveXObject("Microsoft.XMLHTTP")对象
 5             }else{
 6                 xhr = new ActiveXObject("Microsoft.XMLHTTP");
 7             }
 8             return xhr;
 9 
10         }
11 
12         function XhrPostRequest(){
13             var xhr = GetXHR();
14             // 定义回调函数
15             xhr.onreadystatechange = function(){
16                 if(xhr.readyState == 4){
17                     // 已经接收到全部响应数据,执行以下操作
18                     var data = xhr.responseText;
19                     console.log(data);
20                 }
21             };
22             // 指定连接方式和地址----文件方式
23             xhr.open('POST', "/test/", true);
24             // 设置请求头
25             xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset-UTF-8'); #使用POST的方法是需要加一个请求头
26             // 发送请求
27             xhr.send('n1=1;n2=2;');
28         }
29 
30         function XhrGetRequest(){
31             var xhr = GetXHR();
32             // 定义回调函数
33             xhr.onreadystatechange = function(){
34                 if(xhr.readyState == 4){
35                     // 已经接收到全部响应数据,执行以下操作
36                     var data = xhr.responseText;
37                     console.log(data);
38                 }
39             };
40             // 指定连接方式和地址----文件方式
41             xhr.open('get', "/test/", true);
42             // 发送请求
43             xhr.send();
44         }
45         
46     jQuery的ajax提交在返回函数这里
47     success:function(arg,a1,a2)这几个参数里面有一个就是XMLHtt
View Code

相关文章: