Skip to content

Instantly share code, notes, and snippets.

@mrroot5
Created September 22, 2020 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrroot5/381910800f4ebab6d91f50f016975c17 to your computer and use it in GitHub Desktop.
Save mrroot5/381910800f4ebab6d91f50f016975c17 to your computer and use it in GitHub Desktop.
Ajax fetch. Keywords: fetch, fetch api, ajax, axios
fetch('./js/script.js')
.then(function(response) {
// si la promesa de la petición fetch se ha resuelto
// correctamente entrará aquí.
// sin embargo, tal vez el archivo no exista en el servidor (código 404)
// o algún otro problema, por ello debemos de asegurarnos de que todo
// ha ido OK (código 2XX)
if (response.ok) {
// equivale al antiguo success del ajax jquery
// response devuelve una promesa.
// response.json() la respuesta del servidor en formato json
// response.text() la respuesta del servidor en formato texto
const texto = response.text();
const json = response.json();
return { "text_data": ..texto, "json_data": ..json }
} else
// el servidor ha respondido la petición, pero se ha producido algun
// problema y no ha podido enviar el recurso solicitado;
// como por ejemplo que el archivo no existe (404)
return Promise.reject(response.statusText);
}
})
.then(function(responseText) {
// equivale al antiguo complete del ajax jquery
// si la promesa con el texto del script se ha resuelto
// correctamente entrará aquí
loadScr(responseText);
})
.catch(function(error) {
// equivale al antiguo error del ajax jquery
// ha habido algun error al resolver alguna de las promesas
console.log("Error al realizar la petición AJAX: " + error);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment