Created
August 3, 2019 04:10
-
-
Save malcolm-kee/9c8b877a3cd41cbce727fb4722fdb8a4 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
/** | |
* Simple wrapper around XMLHttpRequest to make ajax request | |
* @param {string} url | |
* @param {Object} options | |
* @param {Function} [options.onSuccess] | |
* @param {Function} [options.onError] | |
* @param {string} [options.dataType] default to 'json' | |
* @param {string} [options.method] default to 'GET' | |
*/ | |
function ajax(url, options) { | |
var opts = options || {}; | |
var onSuccess = opts.onSuccess || noop; | |
var onError = opts.onError || noop; | |
var dataType = opts.dataType || 'json'; | |
var method = opts.method || 'GET'; | |
var request = new XMLHttpRequest(); | |
request.open(method, url); | |
if (dataType === 'json') { | |
request.overrideMimeType('application/json'); | |
request.responseType = 'json'; | |
request.setRequestHeader('Accept', 'application/json'); | |
} | |
request.onload = function() { | |
if (request.status >= 200 && request.status < 400) { | |
onSuccess(request.response); | |
} else { | |
onError(request.response); | |
} | |
}; | |
request.onerror = onError; | |
request.send(opts.body); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment