一个简单的Ajax封装类

2010-07-01, Posted in Web 界面, 常用 | 2 回复

在一些小项目中,可能没有使用Jquery这样的js框架,但需要一些js常用的功能,如ajax请求,邮件校验,字符串去空格等,这里封装了一个ajax请求类,在小项目中比较适用.后面给出了一个使用例子.

//类名:AJAX
//创建方法:var ajaxobj=new AJAX;,如果创建失败则返回false
//属性:method  -  请求方法,字符串,POST或者GET,默认为POST
//   url         -  请求URL,字符串,默认为空
//   async     -  是否异步,true为异步,false为同步,默认为true
//   content -  请求的内容,如果请求方法为POST需要设定此属性,默认为空
//   callback  - 回调函数,即返回响应内容时调用的函数,默认为直接返回,回调函数有一个参数为XMLHttpRequest对象,即定义回调函数时要这样:function mycallback(xmlobj)
//方法:send()     -  发送请求,无参数
 
function AJAXRequest() {
	var xmlObj = false;
	var CBfunc,ObjSelf;
	ObjSelf=this;
	try { xmlObj=new XMLHttpRequest; }
	catch(e) {
		try { xmlObj=new ActiveXObject("MSXML2.XMLHTTP"); }
		catch(e2) {
			try { xmlObj=new ActiveXObject("Microsoft.XMLHTTP"); }
			catch(e3) { xmlObj=false; }
		}
	}
	if (!xmlObj) return false;
	this.method="POST";
	this.url;
	this.async=true;
	this.content="";
	this.callback=function(cbobj) {return;}
	this.send=function() {
		if(!this.method||!this.url||!this.async) return false;
		xmlObj.open (this.method, this.url, this.async);
		if(this.method=="POST") xmlObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
		xmlObj.onreadystatechange=function() {
			if(xmlObj.readyState==4) {
				if(xmlObj.status==200) {
					ObjSelf.callback(xmlObj);
				}
			}
		}
		if(this.method=="POST") xmlObj.send(this.content);
		else xmlObj.send(null);
	}
}

使用例子如下

function deleteLogicCompany(logicCompanyid,userid,uName,cName){
	if(confirm( "你要删除分给 '"+uName+"' 的 '"+cName+"' 吗?\n\n        删除数据后,不可恢复,请注意!!!")){
		var ajaxobj=new AJAXRequest;    // 创建AJAX对象
		ajaxobj.method="POST";   // 设置请求方式为GET
		ajaxobj.url="../reportJsp/16ds/deleLogicCompany.jsp"  // 请求的URL
		ajaxobj.content = "logicCompanyid="+logicCompanyid+"&userid="+userid
		ajaxobj.callback=function(xmlobj) {
			var value = xmlobj.responseText;//这里返回的值要看你的请求返回什么东西了.
			var isRepeat = (value == '_yes');
 
			if( !isRepeat ){
				alert('数据已经删除');
				window.location.reload();
			}else{
				alert('数据删除失败');
			}
		}
 
	ajaxobj.send();    // 发送请求
	}
}
标签:

2 Comments for this entry

你也讲两句吧~