Created
August 15, 2019 15:18
-
-
Save fmagrosoto/1e91d8ac94e2a0ccaf10d176d4c7a23d to your computer and use it in GitHub Desktop.
Función sencilla para hacer una consulta vía AJAX usando Javascript sin algún framework
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
// Declarar una variable global para reusarlo a lo largo del script. | |
// Esta variable contendrá el objeto XMLHttpRequest. | |
var httpRequest; | |
/** | |
* FUNCIÓN PARA ACTIVAR AJAX Y HACER LA LLAMADA ASÍNCRONA. | |
* @uses Esta función se dispara al cargarse todos los elementos de la página | |
* @return Void | |
*/ | |
function llamadaAjax() { | |
httpRequest = new XMLHttpRequest(); | |
if (!httpRequest) { | |
console.error('Hay un problema inicializando httpRequest'); | |
return false; | |
} | |
httpRequest.onreadystatechange = mostrarContenido; | |
// httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); | |
// httpRequest.setRequestHeader("Content-Type", "application/json"); | |
httpRequest.open('GET', 'db/datos.json'); // O cualquier otro URL, por ejemplo un API para consumir datos. | |
// httpRequest.open('POST', 'db/datos.json'); | |
httpRequest.send(); | |
// httpRequest.send("foo=bar&lorem=ipsum"); | |
// httpRequest.send(JSON.stringify(JSON.stringify({titulo: "txt", bajada: "txt", url: "txt"}))); | |
} | |
/** | |
* FUNCIÓN QUE SE DISPARA CUANDO AJAX HAYA REGRESADO CON LOS DATOS SOLICITADOS | |
* @return Void | |
*/ | |
function mostrarContenido() { | |
if (httpRequest.readyState === XMLHttpRequest.DONE) { | |
if (httpRequest.status === 200) { | |
var datos = JSON.parse(httpRequest.responseText); | |
[].forEach.call(datos, function (item) { | |
cosole.info(item); | |
}) | |
} else { | |
console.error('Hubo un problema al procesar la solicitud'); | |
} | |
} | |
} | |
// AL CARGARSE TODA LA PÁGINA... | |
window.onload = function () { | |
llamadaAjax(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment