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类型即可