Last active
December 6, 2016 19:29
-
-
Save tokenvolt/6894483 to your computer and use it in GitHub Desktop.
VanillaJS ajax wrapper.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery/18078705#18078705 | |
var ajax = {}; | |
ajax.xhr = function() { | |
try { | |
return new ActiveXObject('Msxml2.XMLHTTP') | |
} catch (e1) { | |
try { | |
return new ActiveXObject('Microsoft.XMLHTTP') | |
} catch (e2) { | |
return new XMLHttpRequest() | |
} | |
} | |
}; | |
ajax.send = function(url, callback, method, data, sync) { | |
var xhr = ajax.xhr(); | |
xhr.open(method, url, sync); | |
xhr.onreadystatechange = function() { | |
if (xhr.readyState == 4) { | |
callback(xhr.responseText) | |
} | |
}; | |
if (method == 'POST') { | |
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
} | |
xhr.send(data) | |
}; | |
ajax.get = function(url, data, callback, sync) { | |
var query = []; | |
for (var key in data) { | |
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); | |
} | |
ajax.send(url + '?' + query.join('&'), callback, 'GET', null, sync) | |
}; | |
ajax.post = function(url, data, callback, sync) { | |
var query = []; | |
for (var key in data) { | |
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key])); | |
} | |
ajax.send(url, callback, 'POST', query.join('&'), sync) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment