废话不多说,直接上代码:
let ajaxRequest = function ({
url,
method = 'GET',
dataType = 'text',
data = null,
success = null,
fail = null,
completed = null,
async = true,
header = {},
}) {
method = method.toLocaleUpperCase();
dataType = dataType.toLocaleLowerCase();
function createXHR() {
if (typeof XMLHttpRequest != "undefined") {
return new XMLHttpRequest();
} else if (typeof ActiveXObject != "undefined") {
if (typeof arguments.callee.activeXString != "string") {
var versions = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp"], i, len;
for (i = 0, len = versions.length; i < len; i++) {
try {
new ActiveXObject(versions[i]);
arguments.callee.activeXString = versions[i];
break;
} catch (ex) {
//跳过
}
}
}
return new ActiveXObject(arguments.callee.activeXString);
} else {
throw new Error("No XHR object available.");
}
}
function makeParams(data, name_prefix = '') {
let paramsStr = '', prefix = '';
if (typeof data == 'object') {
for (var name in data) {
var value = data[name];
if (typeof value == 'object') {
if (name_prefix) {
prefix += '[' + name + ']';
} else {
prefix = name;
}
paramsStr += makeParams(value, name_prefix + prefix);
} else {
if (name_prefix) {
name = name_prefix + '[' + name + ']';
}
paramsStr += encodeURIComponent(name) + "=" + encodeURIComponent(value) + "&";
}
}
} else {
paramsStr += data;
}
return paramsStr;
}
function addURLParam(url, data) {
url += (url.indexOf("?") == -1 ? "?" : "&");
url += makeParams(data);
url = url.replace(/((\s*&\s*)|(\s*?\s*))$/g, '');
return url;
}
this.xhr = createXHR();
this.xhr.onreadystatechange = () => {
console.log(this.xhr.readyState, this.xhr.statusText)
if (this.xhr.readyState == 4) {
let rst = this.xhr.responseText;
if ((this.xhr.status >= 200 && this.xhr.status < 300) || this.xhr.status == 304) {
switch (dataType) {
case 'json':
rst = JSON.parse(rst);
break;
case 'text':
default:
}
if (success) {
success(rst, this.xhr);
}
} else {
rst = new Error(this.xhr.statusText);
if (fail) {
fail(rst, this.xhr);
}
}
if (completed) completed(rst, this.xhr);
}
};
this.xhr.withCredentials = true; // session同步问题
switch (method) {
case 'POST':
data = makeParams(data);
this.xhr.open(method, url, async);
this.xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
break;
default:
if (data && Object.keys(data).length) {
url = addURLParam(url, data);
}
this.xhr.open(method, url, async);
data = null;
}
// 设置请求头
if (Object.keys(header).length) {
for (var name in header) {
this.xhr.setRequestHeader(name, header[name]);
}
}
this.xhr.send(data);
};