封装的AJAX

function AJAX(obj){
//做网络请求的时候,参数以对象的形式传递进来
//规定: obj里面包含属性:1.url; 2.type -- get或是post; 3.data --前端给后端传递的参数(前端传递的时候以"对象"的形式); 4.回调函数---success; 5.回调函数---error


if (obj.callBack) {
var sc = document.createElement("script");
document.documentElement.appendChild(sc);
sc.src = obj.url+"?"+obj.key+"=callBack";//-------------------
return;
}
var ajaxObj = null;
if (window.XMLHttpRequest) {
ajaxObj = new XMLHttpRequest();
}else{
ajaxObj = ActiveXObject("Microsoft.XMLHTTP");
};
ajaxObj.onreadystatechange = function(){
if (ajaxObj.readyState == 4) {
if (ajaxObj.status >= 200 && ajaxObj.status < 300 || ajaxObj.status == 304) {
if (obj.success) {
obj.success(JSON.parse(ajaxObj.responseText));
// obj.success(ajaxObj.responseText); //text,解析
}else{
alert("您忘记了success函数");
}
}else{
if (obj.error) {
obj.error(ajaxObj.status);
}else{
alert("您忘记了error函数");
}
}
}
}
//type转化为小写
var type = obj.type || "get";
type =type.toLowerCase();
//判断是否传递了参数
var params = "";
if (obj.data) {
for (var key in obj.data) {
params += (key + "=" + obj.data[key] + "&");
}
params = params.slice(0,params.length-1);
}
if (type == "get") {
ajaxObj.open(type,obj.url+"?"+params,true);
console.log(obj.url+"?"+params);
ajaxObj.send();
}else{
ajaxObj.open(type,obj.url,true);
ajaxObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajaxObj.send(params);
}
}

原文地址:https://www.cnblogs.com/promiseZ/p/6249685.html