Skip to content

Instantly share code, notes, and snippets.

@allenfantasy
Created January 22, 2016 02:59
Show Gist options
  • Save allenfantasy/4e0c391e86afefb01a80 to your computer and use it in GitHub Desktop.
Save allenfantasy/4e0c391e86afefb01a80 to your computer and use it in GitHub Desktop.
A naive ajax function
// @credit to http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery
function ajax(options) {
if (!options) {
throw new Error('Ajax: options is missing');
}
if (!options.url) {
throw new Error('Ajax: options.url is missing');
}
var async = options.async === undefined ? true : (!!options.async);
var type = options.type || 'GET';
var url = options.url;
var data = options.data ? options.data : null;
var contentType = 'application/x-www-form-urlencoded; charset=UTF-8';
var xhr;
if (window.XMLHttpRequest) {
xhr =new XMLHttpRequest();
} else { // <= IE6
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
xhr.open(type, url, async);
xhr.setRequestHeader('Content-Type', contentType);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status === 200) {
if (typeof options.success === 'function') {
options.success.call(null, xhr.responseText);
}
} else {
if (typeof options.error === 'function') {
options.error.call(null, xhr, xhr.status);
}
}
}
}
xhr.send(data);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment