日期:2014-05-16  浏览次数:20821 次

实现自己的Ajax对象封装器 -- Kajax --第一版完成

第一版 浏览: http://www.iamsese.cn/static/forwardAction.php?action=Kajax

/**
 * Kajax 是自定义的 Ajax封装器
 */
function Kajax(){
	this.XMLHttp = this.getXMLHttpObject();	
}

Kajax.prototype.getXMLHttpObject = function() {
	//define a bool paramter to check IE instance
	var xmlhttp = false ;
	
	//check client brower is IE
	try {
	    // If javascript is greater than 5
	    xmlhttp = new ActiveXObject("MSXML2.XMLHTTP");
	    //alert("You are using Microsoft Internet Explorer .");
	}
	catch (e){
	    //else will use ActiveXObject older version
	    try {
	        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	        //alert("You are using old Microsoft Internet Explorer .");
	    }
	    catch (e){
	         //using brower is no IE.
	         xmlhttp = false ;
	    }
	}
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		try {
	    	xmlhttp = new XMLHttpRequest();
	    	//alert("You are not using Microsoft Internet Explorer .");
		}
		catch(e){
			xmlhttp = false ;
		}
	}
	return xmlhttp ;	
}

Kajax.prototype.get = function (url,isAsyc){
	var outstring = '' ;
	if (isAsyc==undefined) isAsyc=false ;
	if (this.XMLHttp) {		
		this.XMLHttp.open("GET",url,isAsyc);
		var oThis = this.XMLHttp ; //这里复制oThis变量的作用是 不与onreadystatechange函数中的this域冲突
		this.XMLHttp.onreadystatechange = function(){
			if (oThis.readyState == 4 && oThis.status == 200 )
				outstring += oThis.responseText ;
		}
		this.XMLHttp.send(null) ;
	}
	return outstring ;
}
/**
 * 同步获取一个JS文件,并执行
 * @param {} url
 */
Kajax.prototype.getJS = function (url){
	eval(this.get(url));
}

?