function ajaxPromise(method,url,data) {
return new Promise((resolve, reject) => {
var xhr = null;
var method = method || 'GET';
var data = data || null;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open(method, url, true)
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)
}
}
}
if(method == 'GET'){
xhr.send()
}else{
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify(data));
}
})
}
效果展示:
<button id="btn">click</button>
$('#btn').click(function () {
ajaxPromise('GET','http://139.9.107.233:5030/data/data.json',null).catch(err => {
console.log(err);
}).then(res => {
console.log(res)
})
})
来源:CSDN
作者:Jeslie-He
链接:https://blog.csdn.net/Hhjian524/article/details/103999853