Skip to content

Instantly share code, notes, and snippets.

@stan1y
Created March 13, 2012 09:31
Show Gist options
  • Save stan1y/2027823 to your computer and use it in GitHub Desktop.
Save stan1y/2027823 to your computer and use it in GitHub Desktop.
Tiny AJAX lib
ajax = {
getHTTPObject : function() {
var http = false;
//Use IE's ActiveX items to load the file.
if(typeof ActiveXObject != 'undefined') {
try {http = new ActiveXObject('Msxml2.XMLHTTP');}
catch (e) {
try {http = new ActiveXObject('Microsoft.XMLHTTP');}
catch (E) {http = false;}
}
//If ActiveX is not available, use the XMLHttpRequest of Firefox/Mozilla etc. to load the document.
} else if (window.XMLHttpRequest) {
try {http = new XMLHttpRequest();}
catch (e) {http = false;}
}
return http;
},
load : function (url, callback, format, method, data) {
var httpObj = this.init();
if (!method) method = 'GET';
if (!format) format = 'text';
if (!httpObj || !url) return;
if (httpObj.overrideMimeType && format == 'json') {
httpObj.overrideMimeType('application/json');
}
var format = format.toLowerCase();
var method = method.toUpperCase();
//Kill the Cache problem in IE.
var now = 'uid=' + new Date().getTime();
url += (url.indexOf('?') + 1) ? '&' : '?';
url += now;
httpObj.open(method, url, true);
httpObj.onreadystatechange = function () {
if (httpObj.readyState == 4) {
var result = '';
if(httpObj.responseText) {
result = httpObj.responseText;
}
if(format == 'json' && result && JSON) {
result = JSON.parse(result);
}
if(callback) {
callback(httpObj.status, result);
}
}
}
httpObj.send(data);
},
init : function() { return this.getHTTPObject(); }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment