// JavaScript Document
/**
使用方法
<script>
var a = new ajax("get","testajax.php",true,null,callback);
a.setEncVal("dj","丁俊");
a.setEncVal("rt","再来一3个吧");
a.setVal("dd","myname");//不编码
function callback(xmlHttp){
	alert(xmlHttp.responseText);
	alert(xmlHttp.url);
}
a.send();
</script>

*/
function ajax(_method,_url,_async,_params,_func){
	this.xmlhttp=null;
	this.method=_method.toUpperCase();
	this.url=_url;
	this.async=_async;
	this.params=_params;
	this.responseStatus=new Array(2);
	this.responseText=null;
	this.responseXML=null;
	this.func=_func;
	this.createXMLHttpRequest = function(){
			 if (window.ActiveXObject){
			    var axO = ["Msxml3.XMLHTTP", "Msxml2.XMLHTTP", "Msxml.XMLHTTP", "Microsoft.XMLHTTP"], i;
				for (i = 0; i < axO.length; i++) {
						try {
						   this.xmlhttp = new ActiveXObject(axO[i]);
						   break;
						} catch(e) {}
				}  
			 }else if(window.XMLHttpRequest){
			   this.xmlhttp = new XMLHttpRequest();
			 }
	}
	
	this.send = function(){
		this.createXMLHttpRequest();
		this.setVal("_tokens_time",new Date().getTime());
		if(this.method=="GET"){
			if(this.url.indexOf("?")>0){
				this.url +="&"+this.params;	
			}else{
				this.url +="?"+this.params;
			}
			
			this.xmlhttp.open(this.method,this.url,this.async);
		}else{
			this.xmlhttp.open(this.method,this.url,this.async);
			try{
				this.xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
			}catch(e){}
			
		}
		
		var self = this;
		var isFirefox=false;
		if(isFirefox=navigator.userAgent.indexOf("Firefox")>0){
				this.xmlhttp.onload=function() {
				   	self.responseText=self.xmlhttp.responseText;
					self.responseXML=self.xmlhttp.responseXML;
					self.responseStatus[0]=self.xmlhttp.status;
					self.responseStatus[1]=self.xmlhttp.statusText;
					if(typeof(self.func) == "function") {
						self.func(self);
					} else {
						eval(self.func);
					}
				}
		} else{
		
			this.xmlhttp.onreadystatechange = function() {
				if(self.xmlhttp.readyState == 4) {
					self.responseText=self.xmlhttp.responseText;
					self.responseXML=self.xmlhttp.responseXML;
					self.responseStatus[0]=self.xmlhttp.status;
					self.responseStatus[1]=self.xmlhttp.statusText;
					if(typeof(self.func) == "function") {
						self.func(self);
					} else {
						eval(self.func);
					}
					
				}
			}
		}
		if(this.method=="GET"){
			this.xmlhttp.send(null);
		}else{
			this.xmlhttp.send(this.params);	
		}
	}
	
	this.setEncVal=function(_k,_v){
		if(this.params && this.params.length>0){
			this.params+="&"+encodeURIComponent(_k)+"="+encodeURIComponent(_v);
		}else{
			this.params=encodeURIComponent(_k)+"="+encodeURIComponent(_v);	
		}
	}
	this.setVal=function(_k,_v){
		if(this.params!=null && this.params.length>0){
			this.params+="&"+_k+"="+_v;
		}else{
			this.params=_k+"="+_v;	
		}
	}
}



