...

View Full Version : My Ajax Abstraction



Mikebert4
03-21-2012, 12:09 PM
"Ronseal."

I was recently in a situation where I had to optimise the clientside aspect of my ajax calls in a system, after much fettling, I came up with this Ajax abstraction that runs a darn sight quicker than the standard "I just read this over at W3C" way:



/**
* Ajax Abstraction
* @desc called by Ajax([GET||POST],[URL of ajax],[postData],[async],[function]);
*
* @param method {string}, GET or POST
* @param uri {String}
* @param postData {string}
* @param async {boolean}, true or false
* @param function {Object}
*
*/
var Ajax = function() {

function handleReadyState(o, callback) {
if (o && o.readyState == 4 && o.status == 200) {
if (typeof callback == "function") callback(o);
}
}

var getXHR = function() {
var http;
try {
http = new XMLHttpRequest;
getXHR = function() {
return new XMLHttpRequest;
};
}
catch(e) {
var msxml = ['MSXML2.XMLHTTP.3.0', 'MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
for (var i=0, len = msxml.length; i < len; ++i) {
if(isNaN(i)) continue;
try {
http = new ActiveXObject(msxml[i]);
getXHR = function() {
return new ActiveXObject(msxml[i]);
};
break;
}
catch(e) {}
}
}
return http;
};

return function(method, uri, postData, async, callback) {
var http = getXHR();
http.open(method, uri, async || false);
http.onreadystatechange = function(){handleReadyState(http, callback);};
http.send(postData || null);
return http;
};
}();



Just thought I should share - should any of you be looking for a faster ajax call.

two quick examples:

(using GET)


Ajax("GET","ajax.get.php?q=1",null,true, function(o){
alert(o.responseText);
});


(using POST)


Ajax("POST","ajax.get.php","q=1",true, function(o){
alert(o.responseText);
});



M



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum