接上一篇博客,上一篇是以前的jsonp請求方法的封裝,這一篇是xhr請求的簡單封裝。 原理: 1:new一個xhr對象,命名爲ajaxRequest,因爲瀏覽器兼容性的問題,因此將獲取xhr對象的方式封裝爲一個方法,命名爲CreateRequestObject; 2:聲明一個用來發送xhr請求的方法,命名爲obtainData,能夠接收一些參數:url、type、timeout、contentType、data、ready、error等; 3:將傳入的參數進行處理,若某些可選參數沒有傳入,則賦值默認值; 4:發送請求,並根據狀況執行回調。html
/* * xhr 獲取數據 * */ var debug = true; // 是否開啓debug function CreateRequestObject() { var ajaxRequest; try { ajaxRequest = new XMLHttpRequest(); } catch (e) { try { ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try{ ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { ajaxRequest = false; } } } if(!ajaxRequest) { console.log('您的瀏覽器版本太低,請更換最新版本的Chrome瀏覽器!'); } return ajaxRequest; } /* * paramObj { * url: 請求的接口url * type: get/post 請求的方式,可選,默認get * timeout: 設置請求超時時間,可選,默認爲0,即不設置超時 * contentType:設置header,可選 * data: 要發送的數據 * ready: 請求結束後執行 * error: 請求錯誤 * */ function obtainData(paramObj) { var ajaxRequest = CreateRequestObject(); if(ajaxRequest === false) { // 若是獲取ajax對象失敗 return; } // 默認數據的處理 var defaultContentType = 'application/x-www-form-urlencoded; charset=UTF-8'; // var defaultContentType = 'application/json; charset=UTF-8'; var defaultType = 'GET'; var defaultAsync = true; paramObj.contentType = paramObj.contentType || defaultContentType; paramObj.type = paramObj.type || defaultType; // 默認是GET paramObj.async = (typeof paramObj.async === 'boolean') ? paramObj.async : defaultAsync; // 默認是異步 // 設置超時時間 paramObj.timeout && Number(paramObj.timeout) ? ajaxRequest .timeout = paramObj.timeout : ''; // 處理要發送的數據 var senData = paramObj.data ? paramObj.data : ""; if(paramObj.type === "GET") { senData = formatParams(senData); } else if(paramObj.contentType.indexOf('application/x-www-form-urlencoded') > -1) { senData = formatParams(senData); } /*else if(paramObj.contentType.indexOf('application/json') > -1) { // 發送json格式失敗 senData = JSON.stringify(senData); } */else { // 其餘請求方式的數據轉換須要本身實現 } // 發送數據 if(paramObj.type === "GET") { ajaxRequest.open(paramObj.type, paramObj.url + '?' + senData, paramObj.async); ajaxRequest.send(null); } else if(paramObj.type === "POST") { // POST ajaxRequest.open(paramObj.type, paramObj.url, paramObj.async); ajaxRequest.setRequestHeader('Content-Type', paramObj.contentType); ajaxRequest.send(senData); } // 監聽超時事件 ajaxRequest.ontimeout = function () { console.error("The request for " + paramObj.url + " timed out."); }; // 處理返回函數 ajaxRequest.onreadystatechange = function () { if(ajaxRequest.readyState === 4) { if(ajaxRequest.status === 200 || ajaxRequest.status === 304) { var result = ajaxRequest.responseText; try { var data = result ? JSON.parse(result) : false; // 將json字符串轉爲json對象 paramObj.ready? paramObj.ready(data): ''; } catch (e) { console.error(e); } } else { console.error("請求錯誤"); paramObj.error? paramObj.error(): ''; } } }; // 回調函數結束 }