function ajax(opt) {
try {
opt = opt || {};
opt.headers = opt.headers || null;
opt.method = opt.method.toUpperCase() || "POST";
opt.url = opt.url || "";
opt.async = opt.async || true;
opt.data = opt.data || null;
opt.success = opt.success || function () {};
opt.fail = opt.fail || function () {};
var xmlHttp = null;
if (XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var params = [];
for (var key in opt.data) {
params.push(key + "=" + opt.data[key]);
}
var postData = params.join("&");
if (opt.method.toUpperCase() === "POST") {
xmlHttp.open(opt.method, opt.url, opt.async);
xmlHttp.setRequestHeader(
"Content-Type",
"application/x-www-form-urlencoded;charset=utf-8"
);
for (var key in opt.headers) {
xmlHttp.setRequestHeader(key, encodeURI(opt.headers[key]));
}
xmlHttp.send(postData);
} else if (opt.method.toUpperCase() === "GET") {
xmlHttp.open(opt.method, opt.url + "?" + postData, opt.async);
xmlHttp.send(null);
}
xmlHttp.onreadystatechange = function () {
//readyState = 4时表示请求结束
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
// console.log(xmlHttp.responseText);
opt.success(JSON.parse(xmlHttp.responseText)); //如果不是json数据可以去掉json转换
} else {
console.log("2222");
opt.fail(xmlHttp.status + xmlHttp.response);
// console.log("请求失败:" + xmlHttp.status + xmlHttp.response);
}
}
};
} catch (e) {
opt.fail(e);
// console.log(e);
}
}
使用方法
ajax({
method: "POST",
headers: {
aa: "1",
bb: "1"
},
url: "http://www.dd.xx",
data: {
kk:"vv",
xx:"yy"
},
success: function (result) {
console.log(JSON.stringify(result));
},
fail: function (e) {},
});