由于任性不想用jquery 的ajax调用,所以参考了网上的资料写了个javascript 的ajax实现。
var ajax = {};
ajax.x = function () {
if (typeof XMLHttpRequest !== 'undefined') {
return new XMLHttpRequest();
}
var versions = [
"MSXML2.XmlHttp.6.0",
"MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"
];
var xhr;
for (var i = 0; i < versions.length; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
} catch (e) {
}
}
return xhr;
};
ajax.send = function (url, urlParam, method, data,dataType, success, fail, async) {
//console.log(new Date().getTime());
Timer.start();
if (async === undefined) {
async = true;
}
var x = ajax.x();
if (method === 'GET' && urlParam !== undefined) {
x.open(method, url + urlParam, async);
}
else {
x.open(method, url, async);
}
x.onreadystatechange = function () {
if (x.readyState == 4) {
var status = x.status;
if (status >= 200 && status < 300) {
//以下方法是用正则判定 json格式
if (isJSON(x.responseText)) {
var obj = JSON.parse(x.responseText);
success && success(obj, x.responseXML);
}
else {
success && success(x.responseText, x.responseXML);
}
} else {
fail && fail(status);
}
}
};
if (method == 'POST') {
//以下设置是重点,如果需要post json 格式的数据注意设置header格式
if (typeof (dataType) != 'undefined' && dataType != null && dataType == 'json') {
x.setRequestHeader('Content-Type', 'application/json;charset=utf-8'); //设置HTTP header字段值
}
else {
//
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
}
x.send(data)
};
ajax.get = function (url, data, callback, fail, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, (query.length ? '?' + query.join('&') : ''), 'GET', null,null,callback, fail, async);
};
ajax.post = function (url, data, callback, fail,dataType, async) {
Timer.start();
var query = [];
//json 格式
if (typeof (dataType) != 'undefined' && dataType.toLowerCase()== 'json') {
data = JSON.stringify(data);
ajax.send(url, null, 'POST', data,'json', callback, fail, async);
}
else { //非json格式
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, null, 'POST', query.join('&'),null, callback, fail, async);
}
};
//以下代码用于判定是否是json 格式的字符串
function isJSON(str, pass_object) {
if (pass_object && isObject(str)) return true;
if (!isString(str)) return false;
str = str.replace(/\s/g, '').replace(/\n|\r/, '');
if (/^\{(.*?)\}$/.test(str))
return /"(.*?)":(.*?)/g.test(str);
if (/^\[(.*?)\]$/.test(str)) {
return str.replace(/^\[/, '')
.replace(/\]$/, '')
.replace(/},{/g, '}\n{')
.split(/\n/)
.map(function (s) { return isJSON(s); })
.reduce(function (prev, curr) { return !!curr; });
}
return false;
}
function strict(str) {
if (isObject(str)) {
return true;
}
try {
return JSON.parse(str) && true;
} catch (ex) {
return false;
}
}
function isString(x) {
return Object.prototype.toString.call(x) === '[object String]';
}
function isObject(obj) {
return Object.prototype.toString.call(obj) === '[object Object]';
}
调用格式
get: ajax.get('/controller/action', { 'id': 128 }, function (r) { //成功方法},function(r){ //失败方法});
post: ajax.post('/controller/action', { 'id': 122 },function (r) { //成功方法},function(r){ //失败方法});
json post: ajax.post('/controller/action',jsonData,function (r) { //成功方法},function(r){ //失败方法},'json'); //必须要加最后的'json'参数