This would be an example of a call function to Ajax, using Promises.
With our function myAjax()
we can make requests via ajax and get the answer, or the error code, transparently, without the need for libraries like jQuery.
As indicated in the link below:
The previous APIs will be updated to use promises and, if possible,
it will be done so that they are compatible with previous versions.
XMLHttpRequest is a great candidate.
Which means that calls to Ajax through Promises will be much easier in the future. While that arrives, we can use a function like this, passing to the function in parameter the method ( GET, POST
) and the url of the REST service, API, or a php, json or other of our applications.
function myAjax(method, url) {
// Devolver una nueva Promise.
return new Promise(function(resolve, reject) {
// Hacer lo usual de XHR
var req = new XMLHttpRequest();
req.open(method, url);
req.onload = function() {
// Esto es llamado incluso cuando ocurre error 404 etc
// Verificar el status
if (req.status == 200) {
// Resolver la Promise con el texto de respuesta
resolve(req.response);
console.log(req.response);
} else {
// De lo contrario, rechazar con el texto del estatus
reject(Error(req.statusText));
}
};
// Manejar errores de red
req.onerror = function() {
reject(Error("Network Error"));
};
// Hacer la petición
req.send();
});
}
function get(method) {
var url = document.getElementById("datos").value;
myAjax(method, url).then(function(response) {
console.log("¡Correcto!", response);
}, function(error) {
console.error("!Hubo un error!", error);
})
}
Introduzca URL de un servicio REST y pulse Enviar:<br />
<input id="datos" type="text" value="https://api.github.com" size="33" />
<input type="button" onclick="get('GET')" value="Enviar..." />
Links