Ajax工厂模式

两年之后现在终于看得懂这本《Ajax企业级开发》。不敢苟同, 此书翻译十分糟糕。如果不是js精通的人,我想是很难理解到里面某些指代名词是指的什么。我也是十分牵强的才看了大部分。发现它所有的代码都是在围绕一个核心在写。js基础可以的话这种循序渐进的探讨,还是很容易理解的。

下面是我对原书代码略做修改而得。构造XHR时做的判断,基本没做任何带动。并省去了管理事件部分。包括简陋的回调。

 

if (typeof entAjax == "undefined"){       //检查命名空间是否被定义
	entAjax = {};        //设置entAjax为一空的js对象
	}

entAjax.XHRFactory = {         //创建XHRFactory单件对象
	createXHR: function(){        //定义creatXHR()函数,创建XHR
		try {
			if (window.XMLHttpRequest){
				xhr = new XMLHttpRequest();
				}
			else{
				xhr= new ActiveXObject("Microsoft.XMLHTTP");
				}
			}
		catch(e){alert("您的浏览器不支持XHR");}
		return xhr;
		}
	};
	
entAjax.HttpRequest = function(){        //创建HttpRquest类
	this.handler = "";          //请求地址
	this.async = true;           //是否异步
	this.responseType = "xml";            //请求头类型(可以自己设置更多的)
	this.httpObj = entAjax.XHRFactory.createXHR();
	this.completeCallback = null;            //保存回调函数
	this.params = {};            //保存要发送的数据、参数
	}
	
entAjax.HttpRequest.prototype.requestComplete = function(){            //requestComplete方法检查是否调用回调函数
	if (this.httpObj.readyState == 4){
		if (this.httpObj.status == 200){
			this.completeCallback.call(this, this);
			}
		}
	}
	
entAjax.HttpRequest.prototype.get = function(){                //get方法,执行GET请求
	this.httpObj.open("get", this.handler, this.async);
	var _this = this;
	this.httpObj.onreadystatechange = function()
			{_this.requestComplete};
	if (this.responseType == ’xml’)
	this.httpObj.setRequestHeader("Content-type","text/xml");
	this.httpObj.send(null);
	}

entAjax.HttpRequest.prototype.post = function(sData){                //post方法,执行POST请求
	if (sData == null){
		sData = "";
		for (var name in this.params){
			sData += escape(name) + "=" + escape(this.params[name]) + "&";
			}
		sData = sData.substring(0, sData.length-1);
		}
	this.httpObj.open("POST", this.handler, this.async);
	var _this = this;
	this.httpObj.onreadystatechange = function()
			{_this.requestComplete()};
	if (this.responseType == "xml")
	this.httpObj.setRequestHeader("Content-Type", "text/xml");
	this.httpObj.send(sData);
	}

entAjax.HttpRequest.prototype.setParam = function(name, value){            //setParam方法,设置参数、数据
	if (value == null)
	delete this.params[name];
	else
	this.params[name] = value;
	}
	
entAjax.HttpRequest.prototype.abort = function(){                //请求超时方法
	this.httpObj.onreadystatechange = function(){
		this.httpObj.abort();
		}
	}
	
//var xhr = new entAjax.HttpRequest();            //执行get请求实例
//xhr.handler = "ajax/";
//xhr.completeCallback = showResult;
//xhr.get();

//var xhr = new entAjax.HttpRequest();            //执行post请求实例
//xhr.setParam("firstname", "Junior");
//xhr.completeCallback = showResult;
//xhr.handler = "ajax/";
//xhr.post();

function showResult(xhr){            //回调函数,把返回的值添加到id="abcd"的元素里。
	document.getElementById("abcd").innerHTML = xhr.httpObj.responseText;
	}

更多阅读

分类:
|  标签 : 
0 0 vote
Article Rating
Subscribe
提醒
guest
0 评论
Inline Feedbacks
View all comments