const doAjax = Symbol('doAjax');
function randomNum(){
var num = '';
for(var i = 0; i < 20; i++){
num += Math.floor(Math.random() * 10);
}
}
function formDatas(obj){
var str = '';
for(var key in obj){
str += key + '=' +obj[key] + '&';
}
return str.replace(/&$/, '');
}
class HTTP {
[doAjax](options){
//实例化XMLHTTPRequest,并且判断浏览器是否支持XMLHttpRequest,如果不支持就用ActiveXObject('Microsoft.XMLHTTP');
let o = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
//判断浏览器是否支持异步发起HTTP请求
if(!o){
throw new Error('您的浏览器不支持异步发起HTTP请求');
}
//配置配置项
let opt = options || {},
type = (opt.type || 'GET').toUpperCase(),
async = '' + opt.async === 'false' ? false : true,
dataType = opt.dataType || 'JSON',
jsonp = opt.jsonp || 'cb',
jsonpCallback = opt.jsonpCallback || 'JQuery' + randomNum() + '_' + new Date().getTime(),
url = opt.url,
data = opt.data || null,
timeout = opt.timeout || 30000,
error = opt.error || function(){},
success = opt.success || function(){},
complete = opt.complete || function(){},
t = null;
//判断是否含有url,
if(!url){
throw new Error('您没有填写URL');
}
//判断dataType和type,如果dataType为jsonp,type为GET
if(dataType.toUpperCase() === 'JSONP' && type !== 'GET'){
throw new Error('如果dataType为JSONP,那么type请您设置为GET或者不设置');
}
//如果dataType为JSONP
if(dataType.toUpperCase() === 'JSONP'){
var oScript = document.createElement('script'),
oScript.src = url.indexOf('?') === -1
? url + '?' + jsonp + '=' + jsonpCallback
: url + '&' + jsonp + '=' + jsonpCallback;
document.body.appenChild(oScript);
document.body.removeChild(oScript);
window[jsonpCallback] = (data) => {
success(data);
};
return;
}
//调用onreadystatechange
o.onreadystatechange = () => {
if(o.readyState === 4){
if((o.status >= 200 && o.status < 300) || o.status === 304){
switch(dataType.toUpperCase()){
case 'JSON':
success(JSON.parse(o.responseText));
break;
case 'TEXT':
success(o.responseText);
break;
case 'XML':
success(o.responseXML);
break;
default:
success(JSON.parse(o.responseText));
break;
}
}else {
error();
}
complete();
clearTimeout(t);
t = null;
o = null;
}
}
//打开通道
o.open(type, url, async);
type === 'POST' && o.setRequestHeader('Content-type','application/x-www-form-urlencoded');
//发送请求
o.send(type === 'GET' ? null : formDatas(data));
t = setTimeout(() => {
throw new Error('本次请求已超时,API地址为'+ url);
o.abort();
clearTimeout(t);
t = null;
o = null;
},timeout);
}
ajax(opt){
this[doAjax](opt);
}
post(url,data,dataType,successCB,errorCB,completeCB){
this[doAjax]({
type: 'POST',
url: url,
data: data,
dataType: dataType,
success:successCB,
error:errorCB,
complete:completeCB
});
}
get(url,dataType,successCB,errorCB,completeCB){
this[doAjax]({
type: 'GET',
url: url,
dataType: dataType,
success:successCB,
error:errorCB,
complete:completeCB
});
}
}
export { HTTP };
用ES6的方式封装原生Ajax
最新推荐文章于 2022-08-12 16:11:15 发布