Last active
January 18, 2017 16:05
-
-
Save bitsmanent/701ca9a80cf02f1f8b0c to your computer and use it in GitHub Desktop.
Send XMLHttpRequest requests
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
function xhr(method, hdrs, action, data, callback) { | |
var r = new XMLHttpRequest(); | |
r.onreadystatechange = function() { | |
if(r.readyState == 4 && r.status == 200) | |
callback(JSON.parse(r.responseText)); /* always expect JSON */ | |
}; | |
switch(method.toUpperCase()) { | |
case "POST": | |
r.open(method, action, true); | |
if(data && !(data instanceof FormData)) { | |
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); | |
data = serialize(data); | |
} | |
break; | |
case "GET": | |
if(data) { | |
data = serialize(data); | |
action += ((action.indexOf('?') == -1) ? '?' : '&')+data; | |
data = null; | |
} | |
r.open(method, action, true); | |
break; | |
default: | |
console.error(method+": method not supported"); | |
return; | |
} | |
if(hdrs) | |
for(var h in hdrs) | |
r.setRequestHeader(h, hdrs[h]); | |
r.send(data); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment