9.封装Ajax
参照jquery的单例模式
~(function () {
function AJAX(option) {
return new AJAX.prototype.init(option);
};
AJAX.prototype = {
constructor: AJAX,
sendAjax: function () {
this.handelCache();
this.handleData();
let {
url,
method,
async,
data,
success,
error
} = this
let xhr = new XMLHttpRequest();
xhr.open(method, url, async);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (!/^(2|3)\d{2}$/.test(xhr.status)) {
error && error(xhr.statusText, xhr)
} else {
let result = this.handelDataType(xhr)
success && success(result, xhr)
}
}
}
xhr.send(data)
},
handelDataType: function (xhr) {
let dataType = this.dataType.toLocaleUpperCase();
let result = xhr.responseText;
switch (dataType) {
case "TEXT": {
break
}
case "JSON": {
result = JSON.parse(result);
break
}
case "XML": {
result = xhr.responseXML
}
}
return result
},
handelCache: function () {
let {
url,
method,
cache
} = this;
if (/^GET$/i.test(method) && cache.toLocaleLowerCase() === 'false') {
this.toCheck('?') ? url += `&_=${+new Date()}` : url += `?_=${+new Date()}`;
this.url = url;
}
},
handleData: function () {
let {
method,
data
} = this;
if (!data) {
this.data = null
};
if (data != null && typeof data === 'object') {
let str = ``;
for (let k in data) {
if (data.hasOwnProperty(k)) {
str += `${k}=${data[k]}&`
}
}
data = str.length > 0 ? str = str.slice(0, -1) : str
if (/^(GET|DELETE|HEAD|TRACE|OPTIONS)$/i.test(method)) {
this.url += `${this.toCheck('?') ? '&' + data : '?'+data}`;
this.data = null
} else {
this.data = data
}
}
},
toCheck: function (what) {
return this.url.indexOf(what) !== -1 ? true : false
},
}
AJAX.prototype.init = function (option = {}) {
let {
url,
method = "GET",
async = "true",
data = null,
dataType = 'JSON',
cache = "true",
success,
error
} = option;
['url', 'method', 'async', 'data', 'dataType', 'cache', 'success', 'error'].forEach(item =>this[item] = eval(item));
this.sendAjax()
}
AJAX.prototype.init.prototype = AJAX.prototype
window.ajax = AJAX;
})(window)