Skip to content

Instantly share code, notes, and snippets.

@emanoelqueiroz
Last active November 6, 2017 18:35
Show Gist options
  • Save emanoelqueiroz/3deb31a4e624285ce80d009f46164830 to your computer and use it in GitHub Desktop.
Save emanoelqueiroz/3deb31a4e624285ce80d009f46164830 to your computer and use it in GitHub Desktop.
function ajax(obj) {
'use strict';
if (!obj || typeof obj !== 'object') throw new Error('Object parameter is null or undefined.');
obj = {
url: obj.url || null,
type: obj.type || 'json',
method: obj.method || 'GET',
success: obj.success || null
};
function translateType(response) {
switch(obj.type) {
case 'text':
return response;
case 'json':
return JSON.parse(response);
default:
return response;
}
}
let xhr = new XMLHttpRequest();
xhr.open(obj.method, obj.url);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200)
obj.success(translateType(xhr.responseText));
}
xhr.send();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment