Parallele XML-Requests

Alle Requests werden in eine Warteschlange gestellt und der Reihe nach abgearbeitet. Mit dem Parameter channelsize kann man festlegen wie viele Anfragen gleichzeitig gesendet werden sollen.

var request={
	channels:[],
	channelsize:5,
	querys:[],
	init:function(){
		for(var i=0;i<this.channelsize;i++)this.channels[i]=null;
	},
	/**
	 * send a XMLHttpRequest
	 *
	 * @param uri	the uri of the ressource
	 * @param post	post datafield
	 * @param cb	callbackfunction for the response
	 */
	send:function(uri,post,cb){
		this.querys.push({'uri':uri,'post':post,'cb':cb});
		this._run();
	},
	_run:function(){
		if(this.querys.length==0)return;
		for(var i=0;i<this.channelsize;i++){
			if (this.channels[i]===null) {
				var job=this.querys.pop();
				this.channels[i] = new XMLHttpRequest();
				this.channels[i].callback=job.cb;
				this.channels[i].id=i;
				this.channels[i].open((job.post)?'POST':'GET', job.uri, true);
				if(job.post)this.channels[i].setRequestHeader('Content-type','application/x-www-form-urlencoded;Charset=utf-8');
				this.channels[i].onreadystatechange=function(){
					if(this.readyState==4){
						if (this.status==200)eval(this.callback+'(this.responseText)');
						request._clearChannel(this.id);
					}
				}
				this.channels[i].send(job.post);
				break;
			}
		}
	},
	_clearChannel:function(id){
		this.channels[id]=null;
		this._run();
	}
}
request.init();