Since i hate setting global Javascript XMLHttpRequest variables when dealing with AJAX, i decided to roll my own lightweight AJAX class.
The main problem with async callbacks is that the callback loses its reference object, and therefore gets descoped of the original class.
To solve this issue, i wrapped up a better way of dealing the callback supporting both the XMLHttp object itself, and a referal object..
PS: i didnt add the POST method yet, but this should be damn straightforward.
function ajax() {
this.method = 'GET';
}
ajax.prototype = {
// request calls a webservice
// onreadychange, calls the callback function through a inline function
// so the XmlHttpRequest object is transferred (and not lost) since we are not using lame global
// XMLHttpRequest variables.
// Optionally you add an referenceobject to be included.
// Since the callback is normally out of bounds of any object, you can use the reference object within your
// callback function.
request : function(url, callback, referenceobj) {
var xml_obj = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
xml_obj = new XMLHttpRequest();
if (xml_obj.overrideMimeType) {
xml_obj.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
xml_obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xml_obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Cannot create XMLHTTP instance');
}
}
}
if (!xml_obj) {
alert('Cannot create XMLHTTP instance');
return false;
}
prompt('',url);
xml_obj.open('GET',url,true);
xml_obj.onreadystatechange = function() {
if (referenceobj!=null) {
callback(xml_obj, referenceobj);
} else {
callback(xml_obj);
}
};
xml_obj.send(null);
}
}
usage from within any function:
var ajx = new ajax();
ajx.request( url, function(obj,refobject) {
if ((obj.readyState == 4)&&(obj.status == 200)) {
if (refobject.enableJSON==true) {
json_obj = eval( "(" + obj.responseText + ")" );
callback(json_obj);
} else {
callback(obj.responseXML);
}
}
}
, this);
/**/
notice this, is the reference for the callback, so the autononymouse function can handle itself. ;)