对与原生Ajax的封装,依然须要遵循请求的四个步骤:php
1) 建立XMLHttpRequest对象;html
2) 监听onreadstatechange函数;ajax
3) 使用open函数添加参数;浏览器
4) 使用send函数发送请求;缓存
首先,封装建立XHR的函数app
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 }
封装数据处理函数dom
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就已经等装好了,下面调用如下:async
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 }