Estoy escribiendo una página web usando HTML y javascript. He escrito un script (como se ve a continuación) que carga registros desde un archivo json. Mi secuencia de comandos está destinada a cargar datos del archivo json y mostrarse como una alerta de arranque. Cuando lo ejecuté por primera vez, el script funcionó, pero extrañamente las pruebas posteriores no funcionaron. ¿Alguien tiene alguna idea para arreglar esto?
índice.html:
<!DOCTYPE html> <html> <head> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link type="text/css" href="css/style.css" rel="stylesheet"> <!-- Script in Question --> <script type="text/javascript"> // This is a way to load data from a JSON file and load it into places in the html document. Based on: https://howtocreateapps.com/fetch-and-display-json-html-javascript/ fetch('alerts.json') .then(function(response){ return response.json(); }) .then(function (data){ appendData(data); }) .catch(function (err) { console.log(err); }); function appendData(data) { var container = document.getElementById("alerts"); for (let i = 0; i < data.length; i++) { var div = document.createElement("div"); div.className = "alert alert-primary"; div.setAttribute("role", "alert") div.innerHTML = data[i].content; container.appendChild(div) } } </script> <title>Guitars</title> </head> <body> <div id="alerts" style="text-align: center;"> <!-- JSON data appears here --> </div> <div style="text-align: center;" id="main"> <!-- Other stuff here --> </div> <div style="text-align: center;"> <!-- Other stuff here --> </div> </body> </html>alertas.json:
[ {"content":"Welcome back, test1!"}, {"content":"Welcome back, test2!"}, {"content":"Welcome back, test3!"} ] El código lee los registros de alerts.json y los inserta en un div con una identificación de "alertas", como se ve en la etiqueta <script> . ¡Cualquier ayuda sería muy apreciada!
OP aquí. Gracias al usuario @David, se sugirió borrar todos los errores encontrados en la consola de depuración de la página web. Al aclarar esto, ¡la función funcionó según lo previsto!