Last active
December 11, 2015 03:33
-
-
Save tomzmtl/3743a173bcbdb3d84e2a to your computer and use it in GitHub Desktop.
Simple Ajax wrapper (Vanilla JS + Q Promises)
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() | |
{ | |
/** | |
* Serialize and URL-encode provided object. | |
* Note: not recursive, for single-level objects only. | |
* @param Object params | |
* @return String | |
*/ | |
function _serializeParams ( params ) | |
{ | |
return Object.keys(params).map( function(key) | |
{ | |
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]); | |
}) | |
.join('&'); | |
} | |
/** | |
* Check if Promise library is available. | |
* Throws error if not. | |
* @return void | |
* @throws Error | |
*/ | |
function _checkForDependencies () | |
{ | |
if ( typeof Q === 'undefined' ) | |
{ | |
throw new Error('Ajax module requires kriskowal/q'); | |
} | |
} | |
/** | |
* Main request process. | |
* Prepare a XMLHttpRequest object and returns Promise. | |
* The Promise will return the XHR object. | |
* @param String method | |
* @param String url | |
* @param Object data | |
* @return Promise | |
*/ | |
function _request ( method, url, data ) | |
{ | |
_checkForDependencies(); | |
var dfd = Q.defer(), | |
xhr = new XMLHttpRequest(), | |
params = null; | |
xhr.open( method, url ); | |
// automatically setup request to send data as JSON on POST requests | |
// and URL-encoded resource on GET requests. | |
if ( method === 'POST' ) | |
{ | |
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); | |
params = JSON.stringify(data); | |
} | |
else | |
{ | |
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); | |
params = serializeParams(data); | |
} | |
function onStateChange () | |
{ | |
if ( xhr.readyState !== 3 ) | |
{ | |
return; | |
} | |
if ( xhr.status === 200 ) | |
{ | |
dfd.resolve(xhr); | |
} | |
} | |
xhr.onreadystatechange = onStateChange; | |
xhr.send(params); | |
return dfd.promise; | |
} | |
/** | |
* Send a GET request | |
* @param String url | |
* @param Object data | |
* @return Promise | |
*/ | |
function get ( url, data ) | |
{ | |
return _request( 'GET', url, data ); | |
} | |
/** | |
* Send a POST request | |
* @param String url | |
* @param Object data | |
* @return Promise | |
*/ | |
function post ( url, data ) | |
{ | |
return _request( 'POST', url, data ); | |
} | |
/** | |
* Public API | |
* @var Object | |
*/ | |
var api = { | |
post : post, | |
get : get | |
}; | |
return api; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment