(function(window){ function AjaxTool(){} AjaxTool.ajaxRequest = function(params,successCallBack,errCallBack){ /* 獲取傳入的參數 */ //請求的類型 let requestType = params['requestType'] || 'get'; //請求的路徑 let url = params['url']; //傳入的數據 let paramObj = params['paramObj']; //延時請求的處理 let timeout = params['timeout']; //建立一個XMLHttpRequest對象,同時須要考慮兼容性問題 let xhr; if(window.XMLHttpRequest){ xhr = new XMLHttpRequest(); }else{ xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // 轉碼,將網絡請求進行URI的編碼,將請求拿下來以後進行URI的解碼,轉碼以後能夠加強Ajax的健壯性 let codeURI; //判斷請求方式 if(requestType.toLowerCase() === 'get'){ codeURI = encodeURI(url+ '?' +getStrWithObject(paramObj)); xhr.open('get',codeURI,true); xhr.send(); }else if(requestType.toLowerCase() === 'post'){ //獲取請求體 codeURI = encodeURI(getStrWithObject(paramObj)); xhr.open('post',url,true); xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send(codeURI); } //監聽服務器狀態變化 xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ successCallBack(xhr); //清除請求定時器 clearTimeout(timer); }else{ errCallBack(); } } } //處理請求超時問題 let timer; if(timeout > 0){ timer = setTimeout(function(){ //取消請求 xhr.abort(); },timeout); } }; //獲取隨機數 function getRandomStr(){ return Math.random() + (new Date().getTime()); } //將對象轉爲字符串 function getStrWithObject(paramsObj){ let rArr = []; // 遍歷對象 for(let key in paramsObj){ let str = key + "=" +paramsObj[key]; rArr.push(str); } //拼接隨機數 rArr.push('random=' + getRandomStr()); //將數組轉換爲字符串,以&來作分割 return rArr.join('&'); } //經過window.AjaxTool就能夠訪問到AjaxTool方法,這樣能夠防止全局做用域的污染 window.AjaxTool = AjaxTool; })(window);