Tengo un problema. quiero hacer una pagina asi
Ya puedo agregar el número de página al final de la URL. Pero cuando estoy en testing.html/4 y quiero actualizarlo, la página no aparece y muestra el error "No se puede obtener testing.html/4". ¿Cómo hacer que se actualice como de costumbre?
Aquí está mi código
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css"> <style> .spinner { display: none; } </style> </head> <body style="font-size: 60px;"> <div class="news-content"> </div> <div class="loading"> <p>Loading Please Wait</p> </div> <script> function loadData(count) { fetch('/index.json') .then(res => res.json()) .then(json => { if (count < json.length) { let text = document.createElement('p'); text.innerText = json[count].text; document.querySelector('.news-content').append(text); if (count > 0) { history.pushState(null, null, `/testing.html/${count}`) } } }); } let count = 0 window.addEventListener('load', loadData(count)); window.addEventListener('scroll', () => { if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) { count += 1; loadData(count) } }) </script> </body> </html>Me parece que está utilizando archivos HTML puros en un servidor local HTTP/HTTPS. Cuando tiene este tipo de instancia del servidor, no está generando páginas dinámicamente porque no tiene ninguna configuración del lado del servidor detrás del archivo HTML.
Puede hacer esto mediante consultas y, dado que su aplicación no contiene ningún backend de servidor, use el Javascript del cliente para crear un concepto de paginación.
En lugar de tener un sistema de tipo de ruta (que generalmente es manejado por el controlador en el backend), use el sistema de consulta:
Instead of: /testing.html/{PAGE_NUMBER} Use: /testing.html?page={PAGE_NUMBER} Para obtener una consulta de page en Javascript, use la siguiente función:
function getPageNumber() { const urlParams = new URLSearchParams(window.location.search); const page = urlParams.get('page'); return page; }Luego cree una función en la que paginaría los datos (suponiendo que los datos sean una matriz):
function paginateData(data, resultsPerPage, pageNumber) { // Chunk the data based on the limit let result = data.reduce((rows, key, index) => (index % resultsPerPage == 0 ? rows.push([key]) : rows[rows.length-1].push(key)) && rows, []); // Return the current page with index calculation return result[pageNumber - 1]; }Y el código final debería ser algo como esto:
function getData(data) { const RESULTS_PER_PAGE = 2; const currentPageNumber = Number(getPageNumber()); const paginatedData = paginateData(data, RESULTS_PER_PAGE, currentPageNumber); // If paginated data is undefined return first page if (!paginatedData) { /* You can even redirect to /testing.html?page=1 */ return paginateData(data, RESULTS_PER_PAGE, 1); } return paginatedData; } Todo lo que le queda es proporcionar a la función getData un parámetro data que se asemeje a un tipo de matriz.