Stack Overflow Asked by Maria Rodriguez on February 9, 2021
I am trying to show in my index.html the contents of a JSON file I have created using an onload call in the body to a function located in the script.js file. I have finished the function and no data is displayed, and there is an error message in the console that displays "Uncaught ReferenceError: data is not defined
at XMLHttpRequest.ourRequest.onload (script.js:14)"
The error appears if I leave the line that says "ourRequest.send()". If I comment this line, the error won’t show up, but it will still not show the data.
This is my index.html file:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Showing comments stored in json</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body onload="commentLoad()">
<article>
<div class="container"></div>
</article>
<script src="script.js"></script>
</body>
</html>
This is the script.js file:
function commentLoad(){
var textContainer = document.getElementById("container");
var ourRequest=new XMLHttpRequest();
ourRequest.open('GET','comments.json');
ourRequest.onload = function(){
var ourData = JSON.parse(ourRequest.responseText);
var userCommentData = "";
for(i=0;i<data.length;i++){
userCommentData += "<p> User Name: " + ourData[i].name + " Score: " + ourData[i].score + " <p> User Comment: " + ourData[i].comment + "</p> </p>";
}
textContainer.insertAdjacentHTML('beforeend',userCommentData);
}
ourRequest.send();
}
Finally, this is my comments.json file:
[{
"name": "John",
"score": "5",
"comment": "Best thing I have ever tried"
},
{
"nombre": "Tom",
"nota": "4",
"comentario": "Very good"
}
]
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP