AJAX-Community Wiki
   Wiki über "Asynchronous JavaScripting and XML" und Web 2.0    AJAX ForumAJAX WikiAJAX Bücher
 

Dies ist eine alte Version des Dokuments!


Um den globalen namespace sauber zu halten und mehrere parallel laufende Requests zu ermöglichen kann man Closures verwenden:

function request(url, data, type, callback) {
	type = type.toUpperCase();
 
	// try to create a XHR-Instance
	var xhr = false;
	if( window.XMLHttpRequest && ! window.ActiveXObject) {
		xhr = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		try {
			xhr = new ActiveXObject("Msxml2.XMLHTTP");
		} catch(e) {
			try {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			} catch(e) {
				xhr = false;
			}
		}
	}
	//Could not create XHR-object -> incomtabile browser
	if ( ! xhr ) {
		throw 'browser not ajax-capable';
	}
 
	//for GET-Requests append param-string to URL
	if ( type == 'GET' ) {
		url += '?'+data;
	}
 
	//prepare request
	xhr.open(type, url, true);
	xhr.onreadystatechange = function() {
		if( xhr.readyState == 4 && xhr.status == 200 ) {
			callback(xhr);
		}
	};
	xhr.send( type != 'GET' ? data : null );
}

verwendet wird das ganze dann wie folgt:

request('index.php', 'action=foo&bar=123', 'get', function(xhr) {
	alert('antwort: '+xhr.responseText);
});
 
tutorial/encapsulated-ajax.1257782396.txt.gz · Zuletzt geändert: 2010/06/21 12:15 (Externe Bearbeitung)
 
Falls nicht anders bezeichnet, ist der Inhalt dieses Wikis unter der folgenden Lizenz veröffentlicht:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki