/*------------------------------------------
* @ ajax类
------------------------------------------*/
M.ajax.prototype = {
init : function (config) {
var that = this;
that.type = config.type ? config.type.toUpperCase() : "GET";
that.dataType = config.dataType || "html";
that.success = config.success || false;
that.error = config.error || false;
that.url = config.url || "";
that.data = config.data || "";
that.contentType = config.contentType ||"application/x-www-form-urlencoded";
that.cache = config.cache === false ? false : true;
that.request = that.getRequest();
if(M.typeOf( that.data ) == "object"){
var tmp = '';
for(var k in that.data){
tmp+='&'+k+'='+that.data[k];
}
if(tmp)that.data = tmp.replace("&","");
tmp = null;
}
if (that.type == "GET") {
var lj = (that.url.indexOf("?") > -1) ? "&" : "?";
that.url += that.data ? (lj + that.data) : "";
}
if (!that.cache) {
var now = new Date();
now = now.getTime();
var lj = (that.url.indexOf("?") > -1) ? "&" : "?";
that.url += lj + '_=' + now;
}
if (that.request) {
var req = that.request;
req.onreadystatechange = that.bindFunction(that.stateChange, that);
req.open( that.type , that.url, true);
if (that.type == "POST"){
req.setRequestHeader("Content-type", that.contentType);
req.send(that.data);
}else{
req.send(null);
}
}
},
getRequest : function () {
if (window.ActiveXObject)
return new ActiveXObject('Microsoft.XMLHTTP');
else if (window.XMLHttpRequest)
return new XMLHttpRequest();
return false;
},
bindFunction : function (caller, object) {
return function () {
return caller.apply(object, [object]);
};
},
stateChange : function (object) {
that = this;
if (that.request.readyState == 4) {
if (that.request.status == 200) {
if (that.dataType == "json") {
try {
if (typeof JSON === "object") {
var json = JSON.parse(that.request.responseText);
} else {
var json = eval('(' + that.request.responseText + ')');
}
} catch (e) {
if (that.error) {
that.error();
return false;
}
}
if (typeof json === "object") {
if (that.success) {
that.success(json,that.request.status,that.request);
return true;
}
} else {
if (that.error) {
that.error();
return false;
}
}
} else {
if (that.success) {
that.success(that.request.responseText,that.request.status,that.request);
return true;
}
}
} else {
if (that.error) {
that.error(that.request);
return false;
}
}
}
}
}
M.ajax.prototype.init.prototype = M.ajax.prototype;
版权所有:www.meilele.com