function ajax(obj) {
if (!obj.method) obj.method = 'GET'//未指定提交方式的时候,默认为get方式
// 在封装异步方法的时候,最好使用Promise来进行封装,如果要支持async + await在封装的时候可以只是用resolve
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest()//构造实例化对象
xhr.open(obj.method.toLocaleUpperCase(), obj.url)
xhr.setRequestHeader('Content-Type', 'application/json')//请求头
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(!this.responseText ? this.responseText : JSON.parse(this.responseText))//如果添加时没有相应的内容,就填入空字符串''
} else {
reject('请求出现了错误,错误码:' + this.status)//请求错误返回错误码
}
}
}
xhr.send(JSON.stringify(obj.data || {}))
})
}
拿走就行