關於 AJAX 相信都用過,本身動手封裝的也確定有很多,但應該都只是簡單的能夠請求,不能設置同步異步以及返回的數據格式ajax
直接上代碼json
//1.用 ES5 寫 ajax var ajax = function (url,method,data,async,success,error,resType) { //設置變量默認值 method = method || "GET"; async = async || true; data = data || ""; resType = resType || ""; //數據校驗 if(!url || url === ''){ throw new Error('url不能爲空');//throw 用來拋出異常 } if(method==="GET" && data != ""){ throw new Error('請將get請求參數寫在url裏');//因爲時間不太夠再也不寫參數拼接,有興趣的小夥伴能夠本身加參數拼接功能 } //將小寫所有轉換爲大寫 method = method.toUpperCase(); //判斷是不是低版本 IE if (window.XMLHttpRequest) { //是否支持XMLHttpRequsest var xhr = new XMLHttpRequest(); } else { //低版本 IE var xhr = new ActiveXObject("Microsft.XMLHTTP"); } //xmlhttp.open(method,url,async) 請求類型 請求地址 是否異步 xhr.open(method, url, async); //設置請求頭 //判斷是否設置 //循環 headers 設置請求頭 // xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //設置返回數據格式 if(async){//若是設置了同步就不能設置返回數據格式 xhr.responseType = resType; // 在不設置responseType的時候默認爲 text } //send(data) 將請求發送到服務器。 data僅用於post xhr.send(data); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var res = xhr.response; if (xhr.status >= 200 && xhr.status < 300 || xhr.status == 304) { success && success(res); } else { error && error(res); } } } } //url,method,data,async,success,error,resType ajax("1.json","GET","",true,function(res){console.log(res);},function(error){console.log(error);},'json');
請求的 json 文件內容服務器
{ "name": "yhtx1997", "text": "恭喜你測試成功!!!" }
調用效果圖app