function ajax(options){
return new Promise(resolve, reject) => {
let xhr;
// 传入方式默认为对象
options = options || {};
// 默认位GET请求
options.type = (options.type || "GET").toUpperCase();
// 返回值类型默认为 json
options.dataType = options.dataType || 'json';
// 默认为异步请求
options.async = options.async || true;
if(window.XMLHttpRequest){
xhr = new XMLHttpRequest();
}else{
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
let status = xhr.status;
if(status >= 200 && status < 300){
resolve(xhr.responseText);
}else{
reject({
error: xhr.responseText,
status: status
})
}
}
};
if(options.type == 'GET'){
xhr.open("GET", options.url + '?' + params, options.async);
xhr.send(null);
}else if(options.type == 'POST'){
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send(params);
}
}
}
基于promise的ajax
最新推荐文章于 2022-10-22 20:37:01 发布