Created
January 22, 2016 02:59
-
-
Save allenfantasy/4e0c391e86afefb01a80 to your computer and use it in GitHub Desktop.
A naive ajax function
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
// @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