Featured Post

Tablas Responsivas con Bootstrap 5 pc escritorio y dispositivos mobiles

Proyecto web tabla registros (libreria Axios de javascript) await async (peticiones asíncronas) json mysql php bootstrap 5

Proyecto web tabla registros (libreria Axios de javascript) await async (peticiones asíncronas) json mysql php bootstrap 5 

index.php

<!DOCTYPE html>

<html lang="es">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">


<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.2/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>


<title>Document</title>

</head>

<style>

* {

font-family: "Century Gothic";

}

</style>

<body>

<div class="container mt-3">

<table class="table table-striped">

<thead>

<th>Id</th>

<th>Nombre</th>

<th>Precio</th>

</thead>

<tbody id="filas"></tbody>

</table>

</div>

<script>

async function cargar_tabla() {

try {

const respuesta = await axios.get('json_api.php');

let tabla = "";

let campos=respuesta.data.articulos;

for (let i = 0; i < campos.length; i++) {

tabla += "<tr>";

tabla += "<td>" + campos[i].id + "</td>";

tabla += "<td>" + campos[i].nombre + "</td>";

tabla += "<td>" + campos[i].precio + "</td>";

tabla += "</tr>";

}

document.getElementById("filas").innerHTML = tabla;

  } catch (error) {

    console.error(error);

  }

}

cargar_tabla();

</script>

</body>

</html>


json_api.php

<?php

header('Content-Type: application/json; charset=UTF-8');

$conexion=new PDO("mysql:dbname=tienda;host=localhost","root","root");

$conexion->query("SET NAMES 'UTF8'");

$consulta = "SELECT * FROM articulos";

$resultado = $conexion->prepare($consulta);

$resultado->execute();

$articulos = array();

while($registros=$resultado->fetch(PDO::FETCH_ASSOC)){

     $articulos["articulos"][]= $registros;

}

echo json_encode($articulos,JSON_PRETTY_PRINT);

?>


Vista Previa







Post publicado por:


Comentarios