Last active
December 17, 2015 15:10
-
-
Save gmac/5630172 to your computer and use it in GitHub Desktop.
API: ajax('url', callbackFunction?, postData?); --> returns: a handle object with an ".abort();" method for canceling the request.
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
var ajax = (function( root ) { | |
function getRequest() { | |
if (root.ActiveXObject) return new ActiveXObject('Microsoft.XMLHTTP'); | |
else if (root.XMLHttpRequest) return new XMLHttpRequest(); | |
else return null; | |
} | |
return function(url, callback, post) { | |
post = post || ""; | |
var req = getRequest(); | |
if (req) { | |
req.onreadystatechange = function() { | |
if (req.readyState == 4 && callback && typeof callback.call == 'function') { | |
callback(req.responseText); | |
} | |
}; | |
if (post) { | |
req.open("POST", url, true); | |
req.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); | |
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); | |
req.setRequestHeader('Connection', 'close'); | |
} else { | |
req.open("GET", url, true); | |
} | |
req.send(post); | |
} | |
return !req ? null : { | |
abort: function() { | |
req.onreadystatechange = undefined; | |
req.abort && req.abort(); | |
} | |
}; | |
}; | |
}(this)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment