Last active
November 6, 2017 18:35
-
-
Save emanoelqueiroz/3deb31a4e624285ce80d009f46164830 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
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