Promise封裝ajax請求
阿新 • • 發佈:2019-01-30
ES6逐漸流行,用Promise物件封裝一個ajax請求,程式碼如下:
//地址,請求方式,引數,是否非同步,頭部資訊[待續] function ajax(url,type,param,async,header) { return new Promise(function(resolve, reject) { var req = new XMLHttpRequest(); req.onload = function() { if(req.status == 200 || req.status == 304) { resolve(JSON.parse(req.response)); } else { reject(Error(req.statusText)); } }; req.onerror = function() { reject(Error("Network Error")); }; type == null || type.toUpperCase() == 'GET'?type='get':type='post'; param = formatParams(param); param == null || param == ''?url:url=url+'?'+param; async == null || async == true?async=true:async=false; //設定表單提交時的內容型別,未完 //xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); req.open(type,url,async); req.send(); }); function formatParams(data) { var _fpArr = []; for (var _fpName in data) { _fpArr.push(_fpName + "=" + data[_fpName]); } return _fpArr.join("&"); }; }; //呼叫
ajax('http://wthrcdn.etouch.cn/weather_mini','get',{citykey:101010100},true).then(function(response) {
console.log('請求成功~');
console.log(JSON.stringify(response));
}, function(error) {
console.error("Failed!", error);
});
上面的例子只需建立一個Promise物件,呼叫它的resolve()和reject()以及then()方法,then()裡面也可以寫箭頭函式;
【注】如果大家要單獨封裝指定請求的方法,如get()和post(),只需把改下傳參和指定req.open(type,url,async)中的type型別即可