// 用promise来写ajax
function ajax(data) {
const pro = new Promise(function (resolve, reject) {
// 数据结构出来
const { type, url, data = {}, async = true, dataType = 'json' } = data // 判断type 请求方式只能是get / post
if (type.toLowerCase() !== 'get' && type.toLowerCase() !== 'post') throw new Error('请求方式type暂时支持get或者post这两种方式');
// 判断url
if (typeof url !== 'string') throw new Error('请求的接口路径错误');
// 判断data
if (Object.prototype.toString.call(data) !== '[object Object]') throw new Error('前端携带的数据data必须是对象')
// dataType
if (dataType !== 'json' && dataType !== 'string') throw new Error('返回值类型dataType只能是json或者string')
// async
if (typeof async !== 'boolean') throw new Error('ajax同步异步只能用布尔值表示')
// 凭借data里面的数据
let str = ''
for (let key in data) {
str += ${key}=${data[key]}&
}
// 最后多了个&
str = str.substring(0, str.length - 1)
// 新建小黄人
const xhr = new XMLHttpRequest
// get
if (type.toLowerCase() == 'get') {
xhr.open(type, url + '?' + str, async)
xhr.send()
}
// post
else if (type.toLowerCase() == 'post') {
xhr.open(type, url, async)
// 添加头文件
xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded')
xhr.send(str)
}
// 判断状态码
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
const res = xhr.responseText
if (dataType.toLowerCase == 'json') {
res = JSON.parse(res)
}
// promise的resolve方法
resolve(res)
}
}
})
// 放回pro实例
return pro
}
// 进一步封装api
// 例如 login
function login(data) {
return ajax({
url: 'http://43.138.81.225/php/login.php',
type: 'post',
data
})
}
// 简写形式:
const login = data => ajax({
url: 'http://43.138.81.225/php/login.php',
type: 'post',
data
})