Volver
Ctrl+Space
◑
Copiar
Descargar
Restaurar
Ejecutar
Ctrl+Enter
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title>Fetch API — Ejemplo 1</title> <style> body { font-family: Arial, sans-serif; padding: 20px; background: #fff; max-width: 640px; } h3 { margin: 22px 0 8px; font-size: 15px; color: #333; } button { padding: 8px 18px; background: #F7DF1E; border: none; border-radius: 6px; font-weight: bold; cursor: pointer; font-size: 14px; margin: 4px 4px 4px 0; transition: background 0.15s; } button:hover { background: #e6cc00; } button:disabled { background: #eee; color: #aaa; cursor: not-allowed; } .card { border: 1px solid #eee; border-radius: 8px; padding: 16px; margin-top: 12px; background: #fafafa; } .card h4 { margin: 0 0 8px; color: #333; font-size: 15px; } .card p { margin: 4px 0; font-size: 13px; color: #555; } .card .id { display: inline-block; background: #F7DF1E; color: #333; font-size: 11px; font-weight: bold; padding: 2px 8px; border-radius: 10px; margin-bottom: 6px; } .estado { padding: 10px 14px; border-radius: 6px; font-size: 13px; font-family: monospace; margin-top: 10px; } .estado.loading { background: #fffde7; border: 1px solid #F7DF1E; color: #856404; } .estado.ok { background: #f0fdf4; border: 1px solid #86efac; color: #166534; } .estado.err { background: #fef2f2; border: 1px solid #fca5a5; color: #991b1b; } .json-box { background: #1a1a1a; color: #a5b4fc; border-radius: 6px; padding: 14px; font-family: monospace; font-size: 12px; white-space: pre; overflow-x: auto; margin-top: 10px; } .fila { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin-bottom: 8px; } label { font-size: 13px; color: #555; } input[type="number"] { padding: 6px 10px; border: 1px solid #ddd; border-radius: 6px; font-size: 14px; width: 70px; } </style> </head> <body> <h2>Fetch API — GET básico</h2> <h3>1. Fetch con .then() — forma clásica</h3> <button id="btnThen">Cargar post con .then()</button> <div id="resultadoThen"></div> <h3>2. Fetch con async/await — forma moderna</h3> <button id="btnAsync">Cargar post con async/await</button> <div id="resultadoAsync"></div> <h3>3. Elegí un post por ID</h3> <div class="fila"> <label>ID del post (1–100):</label> <input type="number" id="inputId" value="1" min="1" max="100"> <button id="btnId">Buscar</button> </div> <div id="resultadoId"></div> <script> // Fetch API en JavaScript - Ejemplo 1: GET básico const BASE = "https://jsonplaceholder.typicode.com"; // ── Helper: mostrar estado ──────────────────────────────────────────── function setEstado(contenedor, tipo, texto) { contenedor.innerHTML = `<div class="estado ${tipo}">${texto}</div>`; } // ── Helper: renderizar post ─────────────────────────────────────────── function renderPost(post) { return ` <div class="card"> <span class="id">POST #${post.id}</span> <h4>${post.title}</h4> <p>${post.body}</p> </div>`; } // ── 1. Con .then() ──────────────────────────────────────────────────── document.getElementById("btnThen").addEventListener("click", function() { const div = document.getElementById("resultadoThen"); this.disabled = true; setEstado(div, "loading", "⏳ Fetching con .then()..."); fetch(`${BASE}/posts/2`) .then(response => { if (!response.ok) throw new Error(`HTTP ${response.status}`); return response.json(); }) .then(post => { div.innerHTML = renderPost(post); div.innerHTML += `<div class="json-box">${JSON.stringify(post, null, 2)}</div>`; }) .catch(error => { setEstado(div, "err", `❌ Error: ${error.message}`); }) .finally(() => { this.disabled = false; }); }); // ── 2. Con async/await ──────────────────────────────────────────────── document.getElementById("btnAsync").addEventListener("click", async function() { const div = document.getElementById("resultadoAsync"); this.disabled = true; setEstado(div, "loading", "⏳ Fetching con async/await..."); try { const response = await fetch(`${BASE}/posts/3`); if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } const post = await response.json(); div.innerHTML = renderPost(post); div.innerHTML += `<div class="json-box">${JSON.stringify(post, null, 2)}</div>`; } catch (error) { setEstado(div, "err", `❌ Error: ${error.message}`); } finally { this.disabled = false; } }); // ── 3. Por ID dinámico ──────────────────────────────────────────────── document.getElementById("btnId").addEventListener("click", async function() { const id = parseInt(document.getElementById("inputId").value); const div = document.getElementById("resultadoId"); if (isNaN(id) || id < 1 || id > 100) { setEstado(div, "err", "❌ ID debe ser un número entre 1 y 100"); return; } this.disabled = true; setEstado(div, "loading", `⏳ Cargando post #${id}...`); try { const response = await fetch(`${BASE}/posts/${id}`); if (!response.ok) { throw new Error(`No existe el post #${id} (HTTP ${response.status})`); } const post = await response.json(); div.innerHTML = renderPost(post); setEstado(div.querySelector(".estado") || div, "ok", ""); div.innerHTML += `<div class="estado ok">✅ Status: ${response.status} ${response.statusText}</div>`; } catch (error) { setEstado(div, "err", `❌ ${error.message}`); } finally { this.disabled = false; } }); // Enter en el input document.getElementById("inputId").addEventListener("keydown", (e) => { if (e.key === "Enter") document.getElementById("btnId").click(); }); </script> </body> </html>