步骤都差不多,只是新创建了一个Promise对象,成功时调用resolve函数,失败时调用reject函数,然后再将这个promise返回出去
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] + '&'}//去除最后一个¶ms = 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.statusif (status >= 200 && status < 300) {resolve(xhr.responseText)} else {reject(new Error(status))}}}})return promise}