Skip to content

Instantly share code, notes, and snippets.

@emkay
Created November 17, 2011 19:30
Show Gist options
  • Save emkay/1374188 to your computer and use it in GitHub Desktop.
Save emkay/1374188 to your computer and use it in GitHub Desktop.
Ajax Example
var button, button2, button3;
var i, xhr, activeXids = [
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP'
];
if (typeof XMLHttpRequest === "function") {
xhr = new XMLHttpRequest();
} else {
for (i = 0; i < activeXids; i += 1) {
try {
xhr = new ActiveXObject(activeXids[i]);
break;
} catch (e) {}
}
}
xhr.onreadystatechange = function () {
var el = document.getElementById('output');
if (xhr.readyState !== 4) {
return false;
}
if (xhr.status !== 200) {
console.log("Error, status code: " + xhr.status);
return false;
}
el.innerHTML += "<pre>" + xhr.responseText + "<\/pre>";
};
// helper function to build callbacks
function callback(url) {
return function () {
xhr.open("GET", url, true);
xhr.send();
}
}
button = document.getElementById('my_button');
button2 = document.getElementById('my_button2');
// object sniffing
if (document.addEventListener) { // Firefox, Chrome, etc.
button.addEventListener('click', callback('/test'), false);
button2.addEventListener('click', callback('/json'), false);
} else if (document.attachEvent) { //IE
button.attachEvent('onclick', callback('/test'));
button2.attachEvent('onclick', callback('/json'));
} else { // fallback
button.onclick = callback('/test');
button2.onclick = callback('/json');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment