第110天:Ajax原生js封装函数

一、Ajax的实现主要分为四部分:

1、创建Ajax对象

1 // 创建ajax对象
2 var xhr = null;
3 if(window.XMLHttpRequest){
4     xhr = new XMLHttpRequest();
5 } else {
6     //为了兼容IE6
7     xhr = new ActiveXObject('Microsoft.XMLHTTP');
8 }

2、连接服务器

// 连接服务器open(方法GET/POST,请求地址, 异步传输)
xhr.open('GET',  'data.txt',  true);

3、发送请求

// 发送请求
xhr.send();

4、接收返回数据

 1 // 处理返回数据
 2 /*
 3 ** 每当readyState改变时,就会触发onreadystatechange事件
 4 ** readyState属性存储有XMLHttpRequest的状态信息
 5 ** 0 :请求未初始化
 6 ** 1 :服务器连接已建立
 7 ** 2 :请求已接受
 8 ** 3 : 请求处理中
 9 ** 4 :请求已完成,且相应就绪
10 */
11 xhr.onreadystatechange = function(){
12     if(xhr.readyState == 4){
13         /*
14         ** Http状态码
15         ** 1xx :信息展示
16         ** 2xx :成功
17         ** 3xx :重定向
18         ** 4xx : 客户端错误
19         ** 5xx :服务器端错误
20         */
21         if(xhr.status == 200){
22             success(xhr.responseText);
23         } else {
24             if(failed){
25                 failed(xhr.status);
26             }
27         }
28     }
29 }

二、Ajax封装函数:

 1 function Ajax(type, url, data, success, failed){
 2     // 创建ajax对象
 3     var xhr = null;
 4     if(window.XMLHttpRequest){
 5         xhr = new XMLHttpRequest();
 6     } else {
 7         xhr = new ActiveXObject('Microsoft.XMLHTTP')
 8     }
 9  
10     var type = type.toUpperCase();
11     // 用于清除缓存
12     var random = Math.random();
13  
14     if(typeof data == 'object'){
15         var str = '';
16         for(var key in data){
17             str += key+'='+data[key]+'&';
18         }
19         data = str.replace(/&$/, '');
20     }
21  
22     if(type == 'GET'){
23         if(data){
24             xhr.open('GET', url + '?' + data, true);
25         } else {
26             xhr.open('GET', url + '?t=' + random, true);
27         }
28         xhr.send();
29  
30     } else if(type == 'POST'){
31         xhr.open('POST', url, true);
32         // 如果需要像 html 表单那样 POST 数据,请使用 setRequestHeader() 来添加 http 头。
33         xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
34         xhr.send(data);
35     }
36  
37     // 处理返回数据
38     xhr.onreadystatechange = function(){
39         if(xhr.readyState == 4){
40             if(xhr.status == 200){
41                 success(xhr.responseText);
42             } else {
43                 if(failed){
44                     failed(xhr.status);
45                 }
46             }
47         }
48     }
49 }
50  
51 // 测试调用
52 var sendData = {name:'asher',sex:'male'};
53 Ajax('get', 'data/data.html', sendData, function(data){
54     console.log(data);
55 }, function(error){
56     console.log(error);
57 });
原文地址:https://www.cnblogs.com/le220/p/8018610.html