自己实现ajax的js代码

 

/**
* @author Kyle Li
* <br>
* ajax的基类,现在需要用POST传值才能解决中文参数乱码问题(request默认为utf-8编码)
* <br> 
* @version 1.0 
*/
// 声明一个全局对象Namespace,用来注册命名空间
Namespace = new Object();
// 全局对象仅仅存在register函数,参数为名称空间全路径,如"Grandsoft.GEA"
Namespace.register = function(fullNS)
{
    // 将命名空间切成N部分, 比如Grandsoft、GEA等
    var nsArray = fullNS.split('.');
    var sEval = "";
    var sNS = "";
    for (var i = 0; i < nsArray.length; i++)
    {
        if (i != 0) sNS += ".";
        sNS += nsArray[i];
        // 依次创建构造命名空间对象(假如不存在的话)的语句
        // 比如先创建Grandsoft,然后创建Grandsoft.GEA,依次下去
        sEval += "if (typeof(" + sNS + ") == 'undefined') " + sNS + " = new Object();"
    }
    if (sEval != "") eval(sEval);
};
Namespace.register("org.open4j.util.ajax");

org.open4j.util.ajax.KyleAjax=function(url){
	var request=null;				//XMLHttpRequest实例
	this.url="";					//请求的路径
	this.type="POST";				//请求的方式(默认为POST)
	this.data=[];					//提交的参数
	this.async=true;				//是否为异步模式(默认为异步模式)
	this.debug=false;				//是否用调试模式(默认为发布模式debug=false)
    if((typeof(url)!="undefined")&&(url!=null)) this.url=url;
	try{
		request = new XMLHttpRequest();
	}catch(trymicrosoft){
		try{
			request=new ActiveXObject("Msxml2.XMLHTTP");
		}catch(othermicrosoft){
			request=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	this.httpRequest=request;
};
org.open4j.util.ajax.KyleAjax.prototype.send=function(url,type,async,data){
	if((typeof(url)!="undefined")&&(url!=null)) this.url=url;
	if((typeof(type)!="undefined")&&(type!=null)) this.type=type;
	if((typeof(async)!="undefined")&&(async!=null)) this.async=async;
	if((typeof(data)!="undefined")&&(data!=null)) this.data=data;
	
	//判断下是否为get方式 不是get方式的全部改为post方式,这样是为了避免错误参数
	this.type.toUpperCase()=="GET"?this.type="GET":this.type="POST";
	
	//为了防止IE缓存  在参数中加个随机数
	this.data.push({key:"t",value:Math.random()});
	
	//由于js的指针是动态指针,所以为了保存当前对象,就把他交给他的一属性的对象father属性,
	//(father属性是可以由开发人员随便定的,比如你可以叫mother等)
	this.httpRequest.father=this;
	this.httpRequest.onreadystatechange=this.ajax_sumbitemployment;
	var tempData=[];
	//把数组转换成字符串后会有','号,所以要去除掉
	var regToSpace = new RegExp(",","gi");	
	
	if(this.data!=null&&this.data.length>0){
		var count=this.data.length;
		var joinStr="?";
		var linkStr="=";
		try{
			for(var i=0;i<count;i++){
                i==0?joinStr="?":joinStr="&";
				var key=this.data[i].key;
				var value=this.data[i].value;
				if((typeof(key)=="undefined")||key==null){
				 	throw new Error("参数有问题!");
				 	break;
				}
				if((typeof(value)=="undefined")||value==null){
				 	throw new Error("参数有问题!");
				 	break;
				}
				tempData.push(joinStr);
				tempData.push(key);
				tempData.push(linkStr);
				/**
				 * 这样的编码可以在GET方法传参的时候不让中文乱码
				 * 具体的读取方法是:(java代码为例)doGet()方法中
				 * String value=request.getParameter("XXXX");
				 * value=value!=null?new String(value.getBytes("ISO8859-1"),"UTF-8"):null;
				 * 这样获得的就不乱码了
				 */
				if(this.type=="GET")
					tempData.push(encodeURIComponent(value));
				else
					tempData.push(value);
			}
			if(this.type=="GET"){
				this.url+=tempData.toString().replace(regToSpace,"");
			}
		}catch(DataError){
			//出错了就要清除参数列表
			tempData=[];
			if(this.debug){
				alert("您设置的参数可能存在问题!\n我们将不会提交您的参数");
			}
		}
	}
	this.httpRequest.open(this.type,this.url,this.async);
	if(this.httpRequest.readyState==1){
		//只能在XMLHttpRequest对象的readyState为1的时候才能发送
		if(this.type=="GET"){
			this.httpRequest.send(null);
		}else{
			//Post方式传值
			this.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.httpRequest.send(tempData.toString().replace(regToSpace,"").replace("?",""));
		}
	}else{
		KyleAjax.error(this.httpRequest);
	}
};
org.open4j.util.ajax.KyleAjax.prototype.ajax_sumbitemployment=function(){
	if(this.readyState==4){
		//读取完毕
		if(this.status==200){
			//成功
			this.father.success(this.responseText);
		}else{
			this.father.error(this);
		}
	}else if(this.readyState==0){
		//没有初始化
		this.father.error(this);
	}else if(this.readyState==1){
		//通道准备就绪
		if(this.father.debug){
			alert("通道准备就绪");
		}
	}else if(this.readyState==2){
		//正在向服务器发送数据...
		if(this.father.debug){
			alert("正在向服务器发送数据....");
		}
	}else if(this.readyState==3){
		//正在从服务器接收数据中....
		if(this.father.debug){
			alert("正在从服务器接收数据中....");
		}
	}
};
org.open4j.util.ajax.KyleAjax.prototype.success=function(data){
	//成功后代码交给用户自己写
	if(this.debug){
		alert("调用成功!\n返回数据为:"+data);
	}
};
org.open4j.util.ajax.KyleAjax.prototype.error=function(request){
	//调用失败!用户也可以自己再写一次
	if(request.status==404){
		//没有找到请求的资资源
		if(this.debug){
			alert("没找到请求的资源");
		}
	}else if(request.status==500){
		//服务器内部出错
		if(this.debug){
			alert("服务器内部出错");
		}
	}else if(request.status==0){
		//和服务器通信出问题了!
		if(this.debug){
			alert("和服务器通信出了问题");
		}
	}else{
		//其他错误就不一一列举了
		if(this.debug){
			alert("请求出现了其他错误!");
		}
	}
};

 

下面是调用的方式

 var ajax=new org.open4j.util.ajax.KyleAjax("manage/UserAction");
ajax.type="GET";
ajax.data=[
{key:"action",value:"testajax"},
{key:"myvalue",value:document.getElementById("testt").value}
];
ajax.success=function(data){
alert(data);
};
ajax.error=function(request){
if(request.status==0){
alert("老大!我和服务器失去联系了");
}
};
ajax.send();

你可能感兴趣的:(自己实现ajax的js代码)