步骤都差不多,只是新创建了一个Promise对象,成功时调用resolve函数,失败时调用reject函数,然后再将这个promise返回出去
javascript
function ajax(options) {
let promise = new Promise(function (resolve, reject) {
//创建xhr对象
const xhr = new XMLHttpRequest();
//初始化参数的内容
options = options || {};
options.type = (options.type || 'GET').toUpperCase();
options.dataType = options.dataType || 'json';
//处理参数
let str = '';
let params = options.data;
for (let key in params) {
str += key + '=' + params[key] + '&'
}
//去除最后一个&
params = str.slice(0, str.length - 1);
//发起请求
if (options.type === 'GET') {
xhr.open('GET', options.url + '?' + params, true);
xhr.send(null)
} else if (options.type === 'POST') {
xhr.open('POST', options.url, true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
//接收请求
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
let status = xhr.status
if (status >= 200 && status < 300) {
resolve(xhr.responseText)
} else {
reject(new Error(status))
}
}
}
})
return promise
}