使用原生js封装Ajax函数

对与原生Ajax的封装,依然需要遵循请求的四个步骤:

  1) 创建XMLHttpRequest对象;

  2) 监听onreadstatechange函数;

  3) 使用open函数添加参数;

  4) 使用send函数发送请求;

首先,封装创建XHR的函数

 1 /**
 2  * createXHR()
 3  * 创建XHR兼容对象
 4  */
 5 function createXHR() {
 6     if (typeof XMLHttpRequest !== ‘undefined’) {
 7         return new XMLHttpRequest();
 8     }   else if (typeof ActiveXObject !== 'undefined') {
 9         var version = [
10             'MSXML2.XMLHttp.6.0',
11             'MSXML2.XMLHttp.3.0',
12             'MSXML2.XMLHttp'
13         ];
14         for (var i = 0; i < version.length; i++) {
15             try {
16                 return new ActiveXObject(version[i]);
17             } catch(e) {
18                 console.log(e);
19             }
20         }
21     } else {
22         throw new Error('您的系统或者浏览器不支持XHR对象!');
23     }
24 }  

封装数据处理函数

 1 /**
 2  * params(data)
 3  * 处理数据,ajax以参数的形式传递数据
 4  * @ param {any} data  对象形式的数据源
 5  * @ return string 处理完成的数据,字符串
 6  */
 7 function params(data){
 8     var arr = [];
 9     for(var i in data){
10         arr.push(encodeURIComponent(i) + "=" + encodeURIComponent(data[i]));
11     }
12     return arr.join("&");
13 }

开封装Aja函数

 1 /**
 2  * my_ajax(obj)
 3  * 原生封装的Ajax函数
 4  * @ param {any} obj 调用数需要传入的一系列参数,如:url,data等
 5  * @ return null
 6  */
 7 function my_ajax(obj) {
 8     var xhr = createXHR();
 9     obj.url = obj.url + "?rand=" + Math.random(); // 清除缓存,如需要使用缓存数据,可以不写
10     obj.data = params(obj.data);      // 转义字符串
11     if(obj.method === "get"){      // 判断使用的是否是get方式发送
12         obj.url += obj.url.indexOf("?") == "-1" ? "?" + obj.data : "&" + obj.data;
13     }
14     // 异步
15     if(obj.async === true){
16         // 异步的时候需要触发onreadystatechange事件
17         xhr.onreadystatechange = function(){
18             // 执行完成
19             if(xhr.readyState == 4){
20                 callBack();
21             }
22         }
23     }
24     xhr.open(obj.method,obj.url,obj.async);  // false是同步 true是异步 // "demo.php?rand="+Math.random()+"&name=ga&ga",
25     if(obj.method === "post"){
26         xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
27         xhr.send(obj.data);
28     }else{
29         xhr.send(null);
30     }
31     // xhr.abort(); // 取消异步请求
32     // 同步
33     if(obj.async === false){
34         callBack();
35     }
36     // 返回数据
37     function callBack(){
38         // 判断是否返回正确
39         if(xhr.status == 200){
40             obj.success(xhr.responseText);
41         }else{
42             obj.Error("获取数据失败,错误代号为:"+xhr.status+"错误信息为:"+xhr.statusText);
43         }
44     }
45 }

至此,整个与原生的ajax就已经等装好了,下面调用以下:

 1 // 调用自己等装好的my_ajax函数
 2 // 当点击页面时,请求就会发出去;
 3 var html = document.getElementsByTagName("html")[0];
 4 html.onclick = function(){
 5     my_ajax({
 6         "method" : "post",
 7         "url" : "demo.php",
 8         "data" : {
 9             "name" : "gao",
10             "age" : 100,
11             "num" : "12346&598"
12         },
13         "success" : function(data){
14             console.log(data);
15         },
16         "Error" : function(text){
17             console.log(text);
18         },
19         "async" : true //是否异步
20     });
21 }
posted @ 2017-07-12 16:12  疯狂的Object  阅读(366)  评论(0编辑  收藏  举报