在封装js开发包的时候,需要发送ajax请求,又不能强制用户使用jQuery,因此按照jQuery的风格,封装了一个ajax,
将此成果小小的记录一下
tools.ajax = function (params) {
if (!params.url) {
throw "url is empty";
}
//默认设置
var setting = {
type: "get",
async: true,
data: {},
dataType: "json",
contentType: "application/x-www-form-urlencoded"
};
for (var key in params) {
if (params.hasOwnProperty(key)) {
setting[key] = params[key];
}
}
setting.data = getData(setting.contentType, setting.data);
//根据数据类型调用不同方法
setting.dataType == "jsonp" ? ajaxJsonp(setting) : ajaxJson(setting);
function ajaxJsonp(options) {
var callback = "BigMap_" + Math.random().toString().replace(/\D/g, "") + "_" + (new Date().getTime());
var script = document.createElement("script");
script.src = options.url + "?callback=" + callback + "&" + options.data;
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
window[callback] = function (data) {
options.success && options.success(data);
script.parentNode.removeChild(script);
clearTimeout(script.timer);
delete window[callback];
};
script.timer = setTimeout(function () {
clearTimeout(script.timer);
delete window[callback];
options.error && options.error("网络超时");
}, 5000);
}
function ajaxJson(options) {
var xmlHttp;
try {
//IE高版本创建xmlhttp
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (E) {
try {
//IE低版本创建xmlhttp
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
//兼容非IE浏览器,直接创建xmlhttp对象
xmlHttp = new XMLHttpRequest();
}
}
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");
return;
}
} else {
response = xmlHttp.responseText
}
options.success && options.success(response);
} else {
options.error && options.error("Server error");
}
}
};
if (options.type.toUpperCase() === "GET") {
xmlHttp.open("GET", options.url + "?" + options.data, options.async);
xmlHttp.send(null);
} else if (options.type.toUpperCase() === "POST") {
xmlHttp.open("POST", options.url, options.async);
xmlHttp.setRequestHeader("Content-Type", options.contentType);
xmlHttp.send(options.data);
}
}
function getData(contentType, data) {
//如果contentType为application/json,那么传递过来的数据仅仅为json字符串
if (contentType.search("application/json") !== -1) {
return data;
}
if (data) {
var arr = [];
for (var name in data) {
if (data.hasOwnProperty(name)) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
}
arr.push(("t=" + Math.random()).replace(".", ""));
return arr.join("&");
} else {
return null;
}
}
};
其中可能存在不完善和不合理之处,如有发现,请不吝赐教