function postJSON(url, data) {
return new Promise( (resolve, reject) => {
var xhr = new XMLHttpRequest()
xhr.open("POST", url, true)
xhr.datatype = 'json'
xhr.setRequestHeader("Content-type", "application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(JSON.parse(this.responseText), this)
} else {
var resJson = { code: this.status, response: this.response }
reject(resJson, this)
}
}
}
xhr.send(JSON.stringify(data))
})
}
//使用方法
postJSON('API接口','参数').then(data=>{console.log(data)})
JavaScript使用Promise封装Ajax
最新推荐文章于 2022-11-29 14:15:51 发布