I am just starting with JavaScript and jQuery, so I appreciate your help!
I want to read items from a JSON file like this:
{
"items": [
"this",
"that"
]
}
My code (inspired by a number of stackoverflow and jQuery reference example code) looks like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
</head>
<body>
<div id="notification"></div>
<ul id="items"></ul>
<script>
$.get('list.json', {}, function(data, response){
var jsonResult;
try {
jsonResult = JSON.parse(data);
}
catch (e) {
$('div#result').html('<span style="color:red">cannot load data because: "'+e+'"</span>');
};
var items = []
$.each( jsonResult['items'], function( key, val ) {
items.push( "<li id='item-" + key + "'>" + val + "</li>" );
});
/* // this does not work
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "div#notification" );
*/
$('ul#items').html(items.join(""));
});
</script>
</body>
</html>
And it works. Yay.
My questions:
- Is that more or less ok what I nitted? What can be enhanced?
- Why does the commented-out section not work? I took this from https://api.jquery.com/jQuery.getJSON/