ajax实现类
Logger.Reporter = {
/**
* return true if send successfully, else return false
*
* data is a json object e.g. {a: "hello", b: "hi"}
*
* callback(status),
*/
sendReport : function(data, callback){
var strjson = stringify(data);
//alert(strjson);
if(!callback)
callback = this._defaultCallback;
this._callback = callback;
//send data timeout
var timeoutId = setTimeout(this._requestTimeoutCallback, this._requestTimeout);
var xmlHttpRequest = this._getXmlHttpRequest();
var reqParam = this._getRequestPara("POST");
xmlHttpRequest.open(reqParam.method, reqParam.url, reqParam.async);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");
xmlHttpRequest.setRequestHeader("Content-length", strjson.length);
xmlHttpRequest.setRequestHeader("Connection", "close");
xmlHttpRequest.send(strjson);
xmlHttpRequest.onreadystatechange = function(){
//alert(this.readyState +" "+ this.status);
clearTimeout(timeoutId);
if(this.readyState == 4){
callback(this.status == 200);
}
};
},
_requestTimeoutCallback: function(){
var xmlHttp = Logger.Reporter._getXmlHttpRequest();
if(xmlHttp != null){
xmlHttp.onreadystatechange = null;
xmlHttp.abort(); //doesn't work correctly
Logger.Reporter._callback(false);
}
},
/**
* do nothing
*/
_defaultCallback : function(status){
},
_getRequestPara : function(_method){
return {method : _method, url: Config.serverAddr, async : true};
},
_getXmlHttpRequest : function(){
if(this._xmlHttpRequest == null){
if (window.XMLHttpRequest) {
this._xmlHttpRequest = new XMLHttpRequest();
} else {
var MSXML = ['MSXML2.XMLHTTP.5.0', 'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for ( var i = 0; i < MSXML.length; i++) {
try {
this._xmlHttpRequest = new ActiveXObject(MSXML[i]);
} catch (e) {
}
}
}
}
return this._xmlHttpRequest;
},
_xmlHttpRequest : null,
_callback : null,
_requestTimeout : 5000,
_data : null
};
/**
* come from JSON, convert JSON object to string
* @param arg
* @return
*/
function stringify(arg){
var c, i, l, s = '', v;
switch (typeof arg) {
case 'object':
if (arg) {
if (arg instanceof Array) {
for (i = 0; i < arg.length; ++i) {
v = stringify(arg[i]);
if (s) {
s += ',';
}
s += v;
}
&