//接收文本:$$.init({url : "test.php", type : "post", data : "name=john", success : function(result){}});
//接收XML:$$.init({url : "test.xml", type : "get", success : function(result){result.getElementsByTagName()}});
var $$ = {
init : function(p){
this.parameter = p;
this.xhr = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();
this.type = (this.parameter.type === "post" || this.parameter.type === "POST") ? "POST" : ( (this.parameter.type === "get" || this.parameter.type === "GET") ? "GET" : "POST" );
this.dataType = this.parameter.dataType;
this.data = this.parameter.data;
this.url = this.getUrl();
this.isAsync = (this.parameter.isAsync === undefined) ? "TRUE" : "FALSE"; //如果设置为FALSE,则会在返回结果前锁住浏览器
this.success = (this.parameter.success === undefined) ? alert("请指定接收结果的函数") : this.parameter.success;
this.xhr.onreadystatechange = function(){$$.getResponse();};
this.xhr.open(this.type, this.url, this.isAsync);
this.send();
},
getUrl : function(){
if(this.type === "POST"){return this.parameter.url;}
if(this.data === undefined){return this.parameter.url;}
if(this.data.substr(0, 1) === "?"){
return this.parameter.url + this.data;
}else{
return this.parameter.url + "?" + this.data;
}
},
send : function(){
if(this.type === "POST"){
this.xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
this.xhr.send(this.data);
}else{
this.xhr.send();
}
},
getResponse : function(){
if(this.xhr.readyState === 4 && this.xhr.status === 200){
if(this.parameter.dataType === "document"){
this.parameter.success(this.xhr.responseXML);
}else{
this.parameter.success(this.xhr.responseText);
}
}
}
};