用Promise对象封装
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script type="text/javascript">
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;
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);
});
</script>
</body>
</html>
上面的例子只需创建一个Promise对象,调用它的resolve()和reject()以及then()方法,then()里面也可以写箭头函数;