Para este siguiente ejm tenemos que mandar a llamar a la librería Axios, para ello pinchamos en el siguiente enlace:
En la documentación viene el cdn de la última versión, el cual ponemos antes del script donde tenemos toda nuestra programación. Después de incluir la librería Axios, comenzamos a escribir nuestros scripts.
En este capítulo hacemos el método de la lectura, y en los siguientes, los métodos de la inserción, actualización y eliminación.
Sintaxis del archivo crud_axios.html.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>CRUD API REST Axios</title>
</head>
<body>
<h1>CRUD API REST Ajax</h1>
<section id="crud">
<article>
<h2 class="crud-title">Agregar nombre</h2>
<form class="crud-form">
<input type="hidden" name="id" />
<input type="text" name="nombre" placeholder="Nombre" required />
<br />
<input
type="text"
name="constelacion"
placeholder="constelación"
required
/>
<br />
<input type="submit" value="Enviar" />
</form>
</article>
<article>
<h2>Ver nombres</h2>
<table class="crud-table">
<thead>
<tr>
<th>Nombre</th>
<th>Constelación</th>
<th>Acciones</th>
</tr>
</thead>
<tbody></tbody>
</table>
</article>
</section>
<template id="crud-template">
<tr>
<td class="name"></td>
<td class="constellation"></td>
<td>
<button class="edit">Editar</button>
<button class="delete">Eliminar</button>
</td>
</tr>
</template>
<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>
<script>
const d = document,
$table = d.querySelector(".crud-table"),
$form = d.querySelector(".crud-form"),
$title = d.querySelector(".crud-title"),
$template = d.getElementById("crud-template").content,
$fragment = d.createDocumentFragment();
const getAll = async () => {
try {
let res = await axios.get("http://localhost:5555/santos"),
json = await res.data;
json.forEach((el) => {
$template.querySelector(".name").textContent = el.nombre;
$template.querySelector(".constellation").textContent =
el.constelacion;
$template.querySelector(".edit").dataset.id = el.id;
$template.querySelector(".edit").dataset.name = el.nombre;
$template.querySelector(".edit").dataset.constellation =
el.constelacion;
$template.querySelector(".delete").dataset.id = el.id;
let $clone = d.importNode($template, true);
$fragment.appendChild($clone);
});
$table.querySelector("tbody").appendChild($fragment);
} catch (err) {
let message = err.statusText || "Ocurrió un error";
$table.insertAdjacentHTML(
"afterend",
`<p><b>Error ${status}: ${message}/b></p>`
);
}
};
d.addEventListener("DOMContentLoaded", getAll);
</script>
</body>
</html>
