1 /* 2 * ajax方法 3 */ 4 var Ajax = function() { 5 var that = this; 6 //建立異步請求對象方法 7 that.createXHR = function() { 8 if(window.XMLHttpRequest) { //IE7+、Firefox、Opera、Chrome 和Safari 9 return new XMLHttpRequest(); 10 } else if(window.ActiveXObject) { //IE6 及如下 11 var versions = ['MSXML2.XMLHttp', 'Microsoft.XMLHTTP']; 12 for(var i = 0, len = versions.length; i < len; i++) { 13 try { 14 return new ActiveXObject(version[i]); 15 break; 16 } catch(e) { 17 //跳過 18 } 19 } 20 } else { 21 throw new Error('瀏覽器不支持XHR對象!'); 22 } 23 } 24 //初始化數據方法 25 that.init = function(obj) { 26 //初始化數據 27 var objAdapter = { 28 method: 'get', 29 data: {}, 30 success: function() {}, 31 complete: function() {}, 32 error: function(s) { 33 alert('status:' + s + 'error!'); 34 }, 35 async: true 36 } 37 //經過使用JS隨機字符串解決IE瀏覽器第二次默認獲取緩存的問題 38 that.url = obj.url + '?rand=' + Math.random(); 39 that.method = obj.method || objAdapter.method; 40 that.data = that.params(obj.data) || that.params(objAdapter.data); 41 that.async = obj.async || objAdapter.async; 42 that.complete = obj.complete || objAdapter.complete; 43 that.success = obj.success || objAdapter.success; 44 that.error = obj.error || objAdapter.error; 45 } 46 //ajax異步調用 47 that.ajax = function(obj) { 48 that.method = obj.method || 'get'; 49 if(obj.method === 'post'){ 50 that.post(obj); 51 }else{ 52 that.get(obj); 53 } 54 } 55 //post方法 56 that.post = function(obj) { 57 var xhr = that.createXHR(); //建立XHR對象 58 that.init(obj); 59 that.method='post'; 60 if(that.async === true) { //true表示異步,false表示同步 61 //使用異步調用的時候,須要觸發readystatechange 事件 62 xhr.onreadystatechange = function() { 63 if(xhr.readyState == 4) { //判斷對象的狀態是否交互完成 64 that.callback(obj,this); //回調 65 } 66 }; 67 } 68 //在使用XHR對象時,必須先調用open()方法, 69 //它接受三個參數:請求類型(get、post)、請求的URL和表示是否異步。 70 xhr.open(that.method, that.url, that.async); 71 //post方式須要本身設置http的請求頭,來模仿表單提交。 72 //放在open方法以後,send方法以前。 73 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 74 xhr.send(that.data); //post方式將數據放在send()方法裏 75 if(that.async === false) { //同步 76 that.callback(obj,this); //回調 77 } 78 }; 79 //get方法 80 that.get = function(obj) { 81 var xhr = that.createXHR(); //建立XHR對象 82 that.init(obj); 83 if(that.async === true) { //true表示異步,false表示同步 84 //使用異步調用的時候,須要觸發readystatechange 事件 85 xhr.onreadystatechange = function() { 86 if(xhr.readyState == 4) { //判斷對象的狀態是否交互完成 87 that.callback(obj,this); //回調 88 } 89 }; 90 } 91 //如果GET請求,則將數據加到url後面 92 that.url += that.url.indexOf('?') == -1 ? '?' + that.data : '&' + that.data; 93 //在使用XHR對象時,必須先調用open()方法, 94 //它接受三個參數:請求類型(get、post)、請求的URL和表示是否異步。 95 xhr.open(that.method, that.url, that.async); 96 xhr.send(null); //get方式則填null 97 if(that.async === false) { //同步 98 that.callback(obj,this); //回調 99 } 100 } 101 //請求成功後,回調方法 102 that.callback = function(obj,xhr) { 103 if(xhr.status == 200) { //判斷http的交互是否成功,200表示成功 104 obj.success(xhr.responseText); //回調傳遞參數 105 } else { 106 alert('獲取數據錯誤!錯誤代號:' + xhr.status + ',錯誤信息:' + xhr.statusText); 107 } 108 } 109 //數據轉換 110 that.params = function(data) { 111 var arr = []; 112 for(var i in data) { 113 //特殊字符傳參產生的問題能夠使用encodeURIComponent()進行編碼處理 114 arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i])); 115 } 116 return arr.join('&'); 117 } 118 return { 119 post : that.post, 120 get : that.get, 121 ajax : that.ajax 122 } 123 }
上述的Ajax方法能夠當作是一個類,共有方法有:php
1. 初始化數據方法init(),ajax
2. 建立異步請求對象方法createXHR(),json
3.請求方法ajax(),post(),get(),瀏覽器
4.請求成功後回調方法callback(),緩存
5.數據格式轉換方法params()app
也能夠當作一個函數,return 返回的json對象中定義的接口用於函數內方法的調用 dom
故而有有兩種方式進行使用封裝的Ajax異步
函數方式:測試代碼數據async
1 Ajax().post({ 2 url: 'ajax.php', 3 data: { 4 'name': 'JR', 5 'age': 22 6 }, 7 success: function(message) { 8 console.log(message); 9 }, 10 async: true 11 });
類方式:測試代碼數據函數
1 var ajax = new Ajax(); 2 ajax.post({ 3 url: 'ajax.php', 4 data: { 5 'name': 'JR', 6 'age': 22 7 }, 8 success: function(message) { 9 console.log(message); 10 }, 11 async: true 12 });
對上述封裝的ajax方法進行優化
1var Ajax = { 2 //ajax模塊 3 init: function(obj) { 4 //初始化數據 5 var objAdapter = { 6 url: '', 7 method: 'get', 8 data: {}, 9 success: function() {}, 10 complete: function() {}, 11 error: function(s) { 12 alert('status:' + s + 'error!'); 13 }, 14 async: true 15 } 16 //經過使用JS隨機字符串解決IE瀏覽器第二次默認獲取緩存的問題 17 objAdapter.url = obj.url + '?rand=' + Math.random(); 18 objAdapter.method = obj.method || objAdapter.method; 19 objAdapter.data = Ajax.params(obj.data) || Ajax.params(objAdapter.data); 20 objAdapter.async = obj.async || objAdapter.async; 21 objAdapter.complete = obj.complete || objAdapter.complete; 22 objAdapter.success = obj.success || objAdapter.success; 23 objAdapter.error = obj.error || objAdapter.error; 24 return objAdapter; 25 }, 26 //建立XMLHttpRequest對象 27 createXHR: function() { 28 if(window.XMLHttpRequest) { //IE7+、Firefox、Opera、Chrome 和Safari 29 return new XMLHttpRequest(); 30 } else if(window.ActiveXObject) { //IE6 及如下 31 var versions = ['MSXML2.XMLHttp', 'Microsoft.XMLHTTP']; 32 for(var i = 0, len = versions.length; i < len; i++) { 33 try { 34 return new ActiveXObject(version[i]); 35 break; 36 } catch(e) { 37 //跳過 38 } 39 } 40 } else { 41 throw new Error('瀏覽器不支持XHR對象!'); 42 } 43 }, 44 params: function(data) { 45 var arr = []; 46 for(var i in data) { 47 //特殊字符傳參產生的問題能夠使用encodeURIComponent()進行編碼處理 48 arr.push(encodeURIComponent(i) + '=' + encodeURIComponent(data[i])); 49 } 50 return arr.join('&'); 51 }, 52 callback: function(obj, xhr) { 53 if(xhr.status == 200) { //判斷http的交互是否成功,200表示成功 54 obj.success(xhr.responseText); //回調傳遞參數 55 } else { 56 alert('獲取數據錯誤!錯誤代號:' + xhr.status + ',錯誤信息:' + xhr.statusText); 57 } 58 }, 59 ajax: function(obj) { 60 if(obj.method === 'post') { 61 Ajax.post(obj); 62 } else { 63 Ajax.get(obj); 64 } 65 }, 66 //post方法 67 post: function(obj) { 68 var xhr = Ajax.createXHR(); //建立XHR對象 69 var opt = Ajax.init(obj); 70 opt.method = 'post'; 71 if(opt.async === true) { //true表示異步,false表示同步 72 //使用異步調用的時候,須要觸發readystatechange 事件 73 xhr.onreadystatechange = function() { 74 if(xhr.readyState == 4) { //判斷對象的狀態是否交互完成 75 Ajax.callback(opt, xhr); //回調 76 } 77 }; 78 } 79 //在使用XHR對象時,必須先調用open()方法, 80 //它接受三個參數:請求類型(get、post)、請求的URL和表示是否異步。 81 xhr.open(opt.method, opt.url, opt.async); 82 //post方式須要本身設置http的請求頭,來模仿表單提交。 83 //放在open方法以後,send方法以前。 84 xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 85 xhr.send(opt.data); //post方式將數據放在send()方法裏 86 if(opt.async === false) { //同步 87 Ajax.callback(obj, xhr); //回調 88 } 89 }, 90 //get方法 91 get: function(obj) { 92 var xhr = Ajax.createXHR(); //建立XHR對象 93 var opt = Ajax.init(obj); 94 if(opt.async === true) { //true表示異步,false表示同步 95 //使用異步調用的時候,須要觸發readystatechange 事件 96 xhr.onreadystatechange = function() { 97 if(xhr.readyState == 4) { //判斷對象的狀態是否交互完成 98 Ajax.callback(obj, xhr); //回調 99 } 100 }; 101 } 102 //如果GET請求,則將數據加到url後面 103 opt.url += opt.url.indexOf('?') == -1 ? '?' + opt.data : '&' + opt.data; 104 //在使用XHR對象時,必須先調用open()方法, 105 //它接受三個參數:請求類型(get、post)、請求的URL和表示是否異步。 106 xhr.open(opt.method, opt.url, opt.async); 107 xhr.send(null); //get方式則填null 108 if(opt.async === false) { //同步 109 Ajax.callback(obj, xhr); //回調 110 } 111 } 112 };
測試代碼
1 Ajax.post({ 2 url: 'ajax.php', 3 data: { 4 'name': 'JR', 5 'age': 22 6 }, 7 success: function(message) { 8 console.log(message); 9 }, 10 async: true 11 });
ajax.php頁面代碼
1 <?php 2 echo $_POST['name']; 3 ?>
控制檯顯示