JSON - Creating Content with jQuery
Now that we have a sense of JSON and its "object" and "array" structures, let's see how we can create content from JSON using JavaScript.
We'll use the jQuery JavaScript library to build up markup based on data in the JSON structure, and then we'll place it on the page.
We'll use the "seasons" array to build an unordered list of seasons.
The JSON data:
The result we will build:
Let's take a look at the important parts:
HTML:
JavaScript:
var mydata = {"seasons":["Spring", "Summer", "Autumn", "Winter"]};
The JSON data structure. An object with a single name/value pair (name is "seasons" and value is the array of 4 strings)var ul_node = $('<ul>');
Use jQuery syntax to create aul
node,for (var s of mydata.seasons) {
Iterate through the array.var li_node = $('<li>');
Use jQuery syntax to create anli
node.li_node.text(s);
Set the text value of theli
node to be the value of the array item (e.g. first time through the loop, this createsul_node.append(li_node);
Append theli
node to theul
node (e.g. the first time through the loop, we will then have}
this is the curly brace to close the close the loop started infor (var i in seasons) {
$('#seasons_container').append(ul_node);
Finally, once theul
is completed, we append it to the element whose id is#seasons
All Together
Complete markup is: