一个JavaScript异步Http请求类

用JavaScript写了一个异步Http请求类,实现了基本的Http请求功能,可以指定多个完成事件的handler。原理很简单,写它是练手,在window的cscript.exe上跑的。这里贴一下代码。

function $defined(o) {return (o != undefined);}

function print(o) {WScript.Echo(o);}
function Sleep(sec) {WScript.Sleep(1000 * sec);}

Function.prototype.bind = function(obj){
	var method = this;
	return function(){
		return method.apply(obj, arguments);
	};
};

function HttpRequest()
{
	this.privs = {
		httploader: null,
		dispatcher: []
	};

	this.Init = function(args){
		if(!(args instanceof Object))
		{
			throw new Error("Invalid parameter");
		}
		
		var method = "POST";
		var strHttpUrl = null;

		if($defined(args.method))
		{
			method = args.method;
		}

		if($defined(args.url))
		{
			strHttpUrl = args.url;
		}
		else
		{
			throw new Error("No Url");
		}

		if($defined(args.onSuccess))
		{
			var lambda = args.onSuccess;
			this.addDispatcher(lambda);
		}
		else
		{
			throw new Error("No dispacther");
		}

		this.privs.httploader = new ActiveXObject("MSXML2.XMLHTTP");
		this.privs.httploader.open(method, strHttpUrl, true);
		this.privs.httploader.onreadystatechange = (function(){
			if(this.privs.httploader.readyState == 4 &&
			   this.privs.httploader.status == 200)
			{
				for(var idx = 0; idx < this.privs.dispatcher.length; ++idx)
				{
					var lambda = this.privs.dispatcher[idx];
					lambda(this.privs.httploader.responseText);					
				}
			}
		}).bind(this);
	};

	this.send = function(o){
		this.privs.httploader.send(o);
	};

	this.addDispatcher = function(lambda){		
		if(lambda instanceof Function)
		{
			this.privs.dispatcher.push(lambda);
		}
		else if((lambda instanceof Array) && (lambda.length > 0))
		{
			var dispather = this.privs.dispatcher;
			this.privs.dispatcher = dispather.concat(lambda);
		}
		else
		{
			throw new Error("Bad dispatcher");
		}
	};

	this.Init(arguments[0]);
}

function main()
{
	var request = new HttpRequest({
		url: "http://127.0.0.1:81/response.txt",
		method: "POST",
		onSuccess: print
	});

	request.send(null);

	//由于请求是异步执行的,所以这里要主动等待一段时间,不然请求未结束,script就完成退出了。
	Sleep(1);
}

main();

2011-4-8 精简了一下代码,并加入addDispatcher()方法,使得可以增加额外的handler。

posted @ 2011-04-07 12:19  lanyuliuyun  阅读(855)  评论(0)    收藏  举报