I'm still new to JQuery and I'm trying to use it to iterate through a JSON array and update my webpage with the data in the array.
The JSON file looks like this:
[
{
"firstname":"John",
"lastname":"Doe",
"studentnumber":"666"
},
{
"firstname":"Foo",
"lastname":"Bar",
"studentnumber":"777"
}
]
My HTML document looks like this:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery-2.2.3.js"></script>
<script type="text/javascript">
$(document).ready(function(){
console.log('ready');
$.getJSON('us.json', function(data){
$.each(JSON.parse(data), function(key, value){
$.each(value, function(index, member){
html += '<div class="member">';
html += '<h4>' + member.firstname + ' ' + member.lastname +'</h2>';
html += '<p>' + 'has the following member number:' + member.studentnumber + '</p>';
html += '</div>';
console.log(html)
})
});
$('#members').html(html);
});
});
</script>
</head>
<body>
<div>
<h3>Members</h3>
</div>
<div id="members"></div>
</body>
</html>
You can see that I'm trying to use the .each
function to accomplish this task. The above code is giving the following error:
VM2028:1 Uncaught SyntaxError: Unexpected token o
(anonymous function) @ index-v1.html:10
fire @ jquery-2.2.3.js:3187
self.fireWith @ jquery-2.2.3.js:3317
done @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151
After looking at some previous questions here, I tried replacing JSON.parse(data)
with just data
, and this resulted in the following error:
Uncaught ReferenceError: html is not defined
(anonymous function) @ index-v1.html:12
jQuery.extend.each @ jquery-2.2.3.js:371
(anonymous function) @ index-v1.html:11
jQuery.extend.each @ jquery-2.2.3.js:365
(anonymous function) @ index-v1.html:10
fire @ jquery-2.2.3.js:3187
self.fireWith @ jquery-2.2.3.js:3317
done @ jquery-2.2.3.js:8785
(anonymous function) @ jquery-2.2.3.js:9151
What could be causing these problems and how do I fix them?