Skip to content

Instantly share code, notes, and snippets.

@cdiaz
Last active March 7, 2018 00:12
Show Gist options
  • Save cdiaz/4ba5df312ef2654456321589361ed43d to your computer and use it in GitHub Desktop.
Save cdiaz/4ba5df312ef2654456321589361ed43d to your computer and use it in GitHub Desktop.
get and post XMLHttpRequest
function main() {
// ENVIAR DATOS AL SERVIDOR
let data = JSON.stringify({ title: 'foo', body: 'bar', userId: 1 });
SendJSON(data)
// PEDIR DATOS AL SERVIDOR
loadJSON((response) => {
console.log(response);
//ACA PUEDE MANIPULAR LA RESPUESTA
})
}
function SendJSON(data) {
var xobj = new XMLHttpRequest(); // instancia el objeto HttpRequest
xobj.open('POST', 'http://jsonplaceholder.typicode.com/posts');
xobj.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xobj.send(data);
}
function loadJSON(done) {
var xobj = new XMLHttpRequest();
xobj.open('GET', 'http://api.icndb.com/jokes/random?firstName=Cristiam&lastName=Diaz', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == 200) {
done(xobj.responseText);
}
};
xobj.send(null);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment