Last active
April 30, 2020 12:29
-
-
Save bbog/34d67a37989c12dedb9b to your computer and use it in GitHub Desktop.
XHR 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 request = function (options) { | |
// just in case | |
options = options || {}; | |
var url = options.url, | |
method = options.method || 'GET', | |
onSuccess = options.onSuccess, | |
onError = options.onError, | |
params = options.params, | |
formData = options.formData || null, | |
formDataParams = options.formDataParams, | |
credentials = options.credentials || false, | |
xmlResponse = options.xmlResponse || false, | |
jsonResponse = options.jsonResponse || false, | |
asynchronous = options.asynchronous || true, | |
originalResponse = options.originalResponse || false; | |
if (options.onSucces) { | |
onSuccess = options.onSucces; | |
} | |
if (typeof params !== 'undefined') { | |
var paramsParts = []; | |
for (var paramName in params) { | |
var paramValue = params[paramName], | |
paramString = paramName + '=' + paramValue; | |
paramsParts.push(paramString); | |
} | |
var paramsString = paramsParts.join('&'); | |
var urlHasParams = (url.indexOf('?') !== -1); | |
if (urlHasParams) { | |
url += '&' + paramsString; | |
} else { | |
url += '?' + paramsString; | |
} | |
} | |
if (typeof formDataParams !== 'undefined') { | |
var formData = new FormData(); | |
for (var paramName in formDataParams) { | |
formData.append(paramName, formDataParams[paramName]); | |
} | |
} | |
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP'); | |
xhr.onreadystatechange = function () { | |
if (xhr.readyState === 4) { | |
if (xhr.status == 200) { | |
var response = (originalResponse) ? xhr : xhr.responseText; | |
if (xmlResponse) { | |
response = xhr.responseXML; | |
} else if (jsonResponse) { | |
response = JSON.parse(response); | |
} | |
if (onSuccess) { | |
onSuccess(response); | |
} | |
} else { | |
if (onError) { | |
onError(); | |
} | |
} | |
} | |
}; | |
if (credentials) { | |
xhr.withCredentials = true; | |
} | |
if (url) { | |
xhr.open(method, url, asynchronous); | |
try { | |
xhr.send(formData); | |
} catch (e) { | |
if (onError) { | |
onError(); | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment