// e.g., to call, myLib.ajax({url:'process.php?q=hello',success:function(m){alert(m)}});
myLib.ajax = function(opt) { opt = opt || {};
var xhr = (window.XMLHttpRequest) // Usu. ?/|| is for compatibility
? new XMLHttpRequest() // IE7+, Firefox1+, Chrome1+, etc
: new ActiveXObject("Microsoft.XMLHTTP"), // IE 6
async = opt.async || true,
success = opt.success || null, error = opt.error || function(){/*displayErr()*/};
// pass three parameters, otherwise the default ones, to xhr.open()
xhr.open(opt.method || 'GET', opt.url || '', async); // 3rd param true = async
if (opt.method == 'POST')
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// Asyhronous Call requires a callback function listening on readystatechange
if (async)
xhr.onreadystatechange = function(){
if (xhr.readyState == 4) { // 4 is "more ready" than 3 or 2
var status = xhr.status;
if ((status >= 200 && status < 300) || status == 304 || status == 1223)
success && success.call(xhr, xhr.responseText); // raw content of the response
else if (status < 200 || status >= 400)
error.call(xhr);
}
};
xhr.onerror = function(){error.call(xhr)};
// POST parameters encoded as opt.data is passed here to xhr.send()
xhr.send(opt.data || null);
// Synchronous Call blocks UI and returns result immediately after xhr.send()
!async && success && success.call(xhr, xhr.responseText);
};