-
-
Save thure/cccaf10f4d4fc36b84f8 to your computer and use it in GitHub Desktop.
AJAX wrapped in Q as an AMD module with `expect` option.
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
define(['q'], function(Q){ | |
return function(options) { | |
var deferred = Q.defer() | |
, req = new XMLHttpRequest(); | |
req.open(options.method || 'GET', options.url, true); | |
// Set request headers if provided. | |
Object.keys(options.headers || {}).forEach(function (key) { | |
req.setRequestHeader(key, options.headers[key]); | |
}); | |
req.onreadystatechange = function(e) { | |
if(req.readyState !== 4) { | |
return; | |
} | |
if([200,304].indexOf(req.status) === -1) { | |
deferred.reject(new Error('Server responded with a status of ' + req.status)); | |
} else { | |
options.expect = options.expect || 'anything'; | |
switch(options.expect.toLowerCase()){ | |
case 'json': | |
deferred.resolve(JSON.parse(e.target.responseText)); | |
break; | |
case 'xml': | |
deferred.resolve(e.target.responseXML); | |
break; | |
default: | |
deferred.resolve(e.target.responseText); | |
break; | |
} | |
} | |
}; | |
req.send(options.data || void 0); | |
return deferred.promise; | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment