I am writing a webpage using HTML and javascript. I have written a script (as seen below) that loads records from a json file. My script is meant to load data from the json file and display like a bootstrap alert. When I first ran it, the script worked, but strangely subsequent tests did not work. Does anyone have any ideas to fix this?
index.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>
alerts.json:
[
{"content":"Welcome back, test1!"},
{"content":"Welcome back, test2!"},
{"content":"Welcome back, test3!"}
]
The code reads the records from alerts.json and inserts them into a div with an id "alerts" - as seen in the <script> tag. Any help would be greatly appreciated!
OP here. Thanks to user @David, it was suggested to clear out all errors found in the webpage debugging console. Upon clearing these up, the function then worked as intended!