原生 ajax 封装, 可供参考
function promiseAjax(options) {
//解构赋值
const {
type, //请求类型
url, //地址
async = true, //是否异步
data = {}, //携带参数
dataType = 'json' //返回数据格式
} = options;
//判断type url async data 的数据类型是否满足要求
if (type !== 'get' && type !== 'post') {
throw new Error('请求数据类型错误')
}
if (Object.prototype.toString.call(url) !== '[object String]') {
throw new Error('地址数据类型错误')
}
if (Object.prototype.toString.call(async) !== '[object Boolean]') {
throw new Error('是否异步参数类型错误')
}
if (Object.prototype.toString.call(data) !== '[object Object]') {
throw new Error('携带参数类型错误')
}
//拼接地址栏
let str = '';
for (let key in data) {
str += `${key}=${data[key]}`;
}
str = str.substring(0, str.length - 1);
const p = new Promise(resolve => {
//创建ajax请求
const xhr = new XMLHttpRequest();
//判断请求方式是get方式还是post请求方式
//如果是get请求方式直接在地址栏中拼接携带的参数 如果是post请求方式 在发送请求之前需要先设置一个请求头 然后将携带参数写在send中
if (type == 'get') {
xhr.open(type, url + '?' + str)
xhr.send()
}
else {
xhr.open(type, url);
//设置一个请求头
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
//通过send携带参数
xhr.send(str)
}
//等待服务器处理
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let data = xhr.responseText;
//判断返回数据是否为json字符串格式 如果是的话转换为常规数据格式
if (dataType.toLowerCase() === 'json') { //.toLowerCase()为了不区分大小写
data = JSON.parse(res);
}
resolve(data)
}
}
})
return p;
}
测试代码
//测试代码
const p = promiseAjax({
type: 'get',
url: 'http://192.168.60.177/php/list.php',
data: {},
async: true
})