//jQ方法 $.ajax([URL],[OPTIONS])
$.ajax({
url:'',
data:null,
datatype:'json',
method:'GET',
async:true,
cache:true,
success:()=>{},
error:()=>{}
})
//封装成window对象的一个方法。
(function anonymous(window) {
function AJAX(options) {
return new AJAX.prototype.init(options)
}
let init = function init(options = {}){
let {
url,
method = 'GET', //默认值用等号
data = null,
datatype = 'JSON',
async = true,
cache = true,
success,
error } = options;
//MOUNT :将配置挂载到实例上
['url', 'method', 'data', 'datatype', 'async', 'cache', 'success',
'error'
].forEach((item) => {
this[item] = eval(item);
});
//SEND :发送请求
this.sendAjax();
};
AJAX.prototype = {
constructor: AJAX,
init,
//发送AJAX请求
sendAjax() {
this.handleDate();
this.handleCache();
let (method, url, async,error,success,data) = this;
//四部曲
let xhr = new XMLHttpRequest();
xhr.open(method, url, async);
xhr.onreadystatechange = () => {
if (!/^(2|3)\d{2}$/.test(xhr.status)) {
error && error(xhr.statusText, xhr);
return;
}
if (xhr.readyState === 4) {
let result = this.handleDataType(xhr);
success && success(result, xhr);
}
};
xhr.send();
},
//处理DATA-TYPE
handleDataType(xhr) {
let dataType = this.dataType.toUpperCase();
result = xhr.responseText;
switch (dataType) {
case 'TEXT':
break;
case 'JSON':
result = JSON.parse(result);
break;
case 'XML':
xhr.responseXML;
break;
}
return result;
},
//处理CACHE
handleCache() {
let {
url,
method,
cache
} = this;
if (/^GET$/i.test(method) && cache === false) {
url += `${check()}_=${+new Date()}`; //
}
},
//处理DATA
handleData(){
let {data,method} = this;
if(!data) return;
let str = '';
if(typeof data === 'object'){
//如果是对象,转换成x-www-form-urlencoded模式的字符串
for(let key in data){
if(data.hasOwnProperty(key)){
str += `${key}=${data[key]}&`;
}
}
data = str.substring(0,str.length-1);
}
//根据请求方式的不同,传递给服务器的也不同
if(/^(GET|DELETE|HEAD|TRACT|OPTIONS)$/i.test(method)){
this.url += `${this.check()}${data}`;
this.data = null;
return;
}
//当请求为POST时
this.data = data;
},
//检测问号
check() {
return this.url.indexOf('?')>-1?'&':'?';
}
}
init.prototype = AJAX.prototype;
window.ajax = AJAX;
})(window)
//直接ajax(options),options为一个对象