JavaScript之封装Ajax函数
var ajax=function(opt={}){
opt.url = opt.url || "";
opt.method = opt.method || "GET";
opt.async = opt.async || true;
opt.data = opt.data || {};
opt.success = opt.success || function (response) { console.log(response) };
opt.error = opt.error || function (response) { console.log(response) };
let xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
}
let params = [];
for (let key in opt.data) {
params.push(key + "=" + opt.data[key]);
}
const postData = params.join("&");
if (opt.method.toUpperCase() === "POST") {
xmlHttp.open("POST", opt.url, opt.async);
xmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8');
xmlHttp.send(postData);
} else if (opt.method.toUpperCase() === "GET") {
xmlHttp.open("GET", opt.url + '?' + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = () => {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
opt.success(xmlHttp.responseText);
}
else if (xmlHttp.readyState == 4 && xmlHttp.status == 404) {
opt.error(xmlHttp.responseText);
}
}
}