Created
October 3, 2014 22:18
-
-
Save snapwich/cae05a08a9635a99a00f to your computer and use it in GitHub Desktop.
This file contains hidden or 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
angular.module("xhr", []) | |
.factory("xhr", function($window, $q) { | |
return function(opts) { | |
var deferred = $q.defer(), | |
XHR_DONE = 4; // can't use XMLHttpRequest.DONE since some awful libraries overwrite window.XMLHttpRequest | |
// defaults | |
opts = angular.extend({ | |
// url: www.google.com, | |
// success: function() {}, | |
// fail: function() {}, | |
method: "GET", | |
async: true, | |
data: null | |
}, opts); | |
opts.headers = angular.extend({ | |
//'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' | |
}, opts.headers || {}); | |
// For IE9 support, if available use XDomainRequest instead of XMLHttpRequest. | |
var useXDomainRequest = $window.XDomainRequest && ($window.XMLHttpRequest && new $window.XMLHttpRequest().responseType === undefined), | |
xmlhttp; | |
function handler() { | |
setTimeout(function() { // this timeout fixes a weird bug with xmlhttp not being up-to-date in chrome | |
if (xmlhttp.readyState === XHR_DONE) { | |
if (/^2\d+$/.test(xmlhttp.status)) { | |
opts.success && opts.success(xmlhttp); | |
deferred.resolve(xmlhttp); | |
} else { | |
opts.fail && opts.fail(xmlhttp); | |
deferred.reject(xmlhttp); | |
} | |
} | |
}); | |
} | |
if(useXDomainRequest) { | |
xmlhttp = new $window.XDomainRequest(); | |
xmlhttp.onload = handler; | |
} else { | |
xmlhttp = new $window.XMLHttpRequest(); | |
xmlhttp.onreadystatechange = handler; | |
} | |
xmlhttp.open(opts.method, opts.url, opts.async); | |
if(opts.timeout && opts.async) { | |
xmlhttp.timeout = opts.timeout; | |
} | |
angular.forEach(opts.headers, function(value, key) { | |
xmlhttp.setRequestHeader(key, value); | |
}); | |
xmlhttp.send(opts.data); | |
return angular.extend(deferred.promise, { | |
xmlhttp: xmlhttp | |
}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment