標籤:params hang content send response ajax 服務端 調用 pre
封裝 Ajax
因為Ajax 使用起來比較麻煩,主要就是參數問題,比如到底使用GET 還是POST;到
底是使用同步還是非同步等等,我們需要封裝一個Ajax 函數,來方便我們調用。
封裝支援接收來自服務端的資料,不可以發送資料到服務端
/*** 此封裝只支援接收來自服務端的資料,不可以發送資料到服務端 */function ajax(obj) { var xhr = new XMLHttpRequest(); obj.url = obj.url + ‘?rand=‘ + Math.random(); xhr.open(obj.method, obj.url, obj.async); xhr.send(null); if (obj.async === false) { callback(); } if (obj.async === true) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { callback(); } }; } function callback () { if (xhr.status == 200) { obj.success(xhr.responseText); //回調 } else { alert(‘資料返回失敗!狀態碼:‘ + xhr.status + ‘,狀態資訊:‘ + xhr.statusText); } }}
把上面的代碼封裝在ajax2.js中,在頁面上引入該檔案。
<!DOCTYPE html><html><head> <title>Ajax的封裝</title> <meta charset="utf-8"> <script src="ajax2.js"></script></head><body><button id="btn">調用Ajax</button><script> document.getElementById("btn").onclick=function(){ ajax({ method : ‘get‘, url : ‘http://localhost:3000/api/2‘, success : function (text) { alert(text); }, async :false }); };</script></body></html>7.2 封裝支援接收來自服務端的資料,又可以發送資料到服務端function ajax(obj) { var xhr = new XMLHttpRequest(); obj.url = obj.url + ‘?rand=‘ + Math.random(); obj.data = params(obj.data); if (obj.method === ‘get‘) { obj.url = obj.url.indexOf(‘?‘) == -1 ? obj.url + ‘?‘ + obj.data : obj.url + ‘&‘ + obj.data; } if (obj.async === true) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { callback(); } }; } xhr.open(obj.method, obj.url, obj.async); if (obj.method === ‘post‘) { xhr.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded‘); xhr.send(obj.data); } else { xhr.send(null); } if (obj.async === false) { callback(); } function callback () { if (xhr.status == 200) { obj.success(xhr.responseText); //回調 } else { alert(‘資料返回失敗!狀態碼:‘ + xhr.status + ‘,狀態資訊:‘ + xhr.statusText); } }} //名值對編碼function params(data) { var arr = []; for (var i in data) { arr.push(encodeURIComponent(i) + ‘=‘ + encodeURIComponent(data[i])); } return arr.join(‘&‘);}
希望能夠幫到你!
Ajax的封裝。