您的位置:首页 > Web前端 > JavaScript

JavaScript - ajax请求的初步封装

2016-07-04 14:52 375 查看
在封装js开发包的时候,需要发送ajax请求,又不能强制用户使用jQuery,因此按照jQuery的风格,封装了一个ajax,

将此成果小小的记录一下

BigMap.ajax = function(options) {
if (!options.url) {
throw "url is empty";
}

var xmlHttp;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");//IE高版本创建XMLHTTP
} catch(E) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//IE低版本创建XMLHTTP
} catch(E) {
xmlHttp = new XMLHttpRequest();//兼容非IE浏览器,直接创建XMLHTTP对象
}
}

options.type = (options.type || "GET").toUpperCase();
options.dataType = options.dataType || "json";
options.async = options.async == undefined ? true : options.async;
options.data = (function(data){
if (data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
arr.push(("t=" + Math.random()).replace(".",""));
return arr.join("&");
} else {
return null;
}
})(options.data);

xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var response;
if (options.dataType == "json") {
try{
response = eval("(" + xmlHttp.responseText + ")");
} catch(e) {
options.error && options.error("JSON parsing failed");
}

} else {
response = xmlHttp.responseText
}
options.success && options.success(response);
} else {
options.error && options.error("Server error");
}
}
}

if (options.type == "GET") {
xmlHttp.open("GET", options.url + "?" + options.data, options.async);
xmlHttp.send(null);
} else if (options.type == "POST") {
xmlHttp.open("POST", options.url, options.async);
xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlHttp.send(options.data);
}
}


其中可能存在不完善和不合理之处,如有发现,请不吝赐教
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ajax