Reputation: 77
How do I display json data in a list using jQuery?
$(document).ready(function() {
$.getJSON('example.json', function(data) {
$.each(data.example, function(key, value) {
var output="";
output="<li>" + data.example[key].name + "</li>";
$('#example').append(output);
});
});
}
This doesn't seem to display anything.
Upvotes: 0
Views: 2130
Reputation: 3151
$(document).ready(function() {
$.getJSON('example.json', function(data) {
var output = '';
$.each(data.example, function(key, value) {
output += '<li>' + value.name + '</li>';
});
$('#example').html(output); // <ul id="example"></ul>
});
});
UPDATE: Working JSON file
{
"example": [
{
"name": "Dr. Sammie Boyer",
"email": "[email protected]"
},
{
"name": "Eladio Beier",
"email": "[email protected]"
},
{
"name": "Hilton Borer",
"email": "[email protected]"
}
]
}
Upvotes: 1
Reputation: 14031
This would be my take.
You have multiple syntax errors (which are hard to see because the code is poorly formatted) - formatting the code helps you see those errors.
Note: I avoided making the AJAX call to get the JSON data for the looping parsing example.
$(document).ready(function() {
var data = {
"example": [{
"name": "Dr. Sammie Boyer"
}, {
"name": "Eladio Beier",
"email": "[email protected]"
}, {
"name": "Hilton Borer",
"email": "[email protected]"
}]
};
// we don't have to get the json in an AJAX call for this demo
// $.getJSON('example.json', function(data) {
var output = "<ul>";
$.each(data.example, function(key, value) {
output += "<li>" + value.name + "</li>";
});
output += "</ul>";
$('#example').append(output);;
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="example"></div>
Upvotes: 0
Reputation: 1
You have a couple of syntax errors. The comma in the each function is in the wrong place and there's no closing ); at the end. The code below should work correctly...
$(document).ready(function() {
$.getJSON('example.json', function(data) {
$.each(data.example, function(key, value) {
var output="";
output="<li>" + data.example[key].name + "</li>";
$('#example').append(output);
});
});
});
Upvotes: 0