function formatParams(data) {
var arr = [];
for (var name in data) {
arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
}
return arr.join("&");
}
function jsonAjax(options) {
options = options || {};
options.type = (options.type || 'GET').toUpperCase();
options.dataType = options.dataType || 'json';
var params = formatParams(options.data);
var xhr, sp;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveObject) { //IE6及以下
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
if (options.type == 'GET') {
sp = options.url.indexOf('?')>-1?'&':'?';
xhr.open('GET', options.url+sp+params);
xhr.send(null);
} else if (options.type == 'POST') {
xhr.open('POST', options.url);
xhr.send(JSON.stringify(options.data));
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var status = xhr.status;
if (status >= 200 && status < 300 || status == 304) {
if (options.dataType == "json") {
options.success && options.success(JSON.parse(xhr.responseText), xhr.responseXML);
} else {
options.success && options.success(xhr.responseText, xhr.responseXML);
}
} else {
options.error && options.error(status);
}
}
}
}