![]() |
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);
});