En el capítulo anterior estuvimos haciendo un CRUD con Ajax, mediante la técnica del objeto XMLHttpRequest, en este capítulo seguimos trabajando la misma API falsa, y en este capítulo vamos a utilizar la técnica de FETCH más funciones asíncronas, veamos la sintaxis de este ejercicio.
Sintaxis de crud_fetch.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 Ajax</title> </head> <body> <h1>CRUD API REST FETCH</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>Email</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> 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 fetch("http://localhost:5555/santos"), json = await res.json(); if (!res.ok) throw { status: res.status, statusText: res.statusText }; console.log(json); 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.insertAdjacentElement( "afterend", `<p><b>Error ${err.status}: ${message}</b></p>` ); } }; d.addEventListener("DOMContentLoaded", getAll); </script> </body> </html>