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 seasons = mydata.seasons;
Create a variableseasonsthat is equal tomydata.seasons. At this point, the variableseasonsis equal to["Spring", "Summer", "Autumn", "Winter"]var ul_node = $('<ul>');
Use jQuery syntax to create aulnode,
for (var i in seasons) {
Iterate through the array via index position. Remember that arrays in JavaScript (as in almost all programming languages) begin with an index of 0. Therefore, the first time through this loop,iwill be0, the second time,iwill be1, etc. And to access the value of the array,seasons[i]will be used —seasons[0]isSpringandseasons[1]isSummer, etc.var li_node = $('<li>');
Use jQuery syntax to create anlinode.li_node.text(seasons[i]);
Set the text value of thelinode to be the value of the array item (e.g. first time through the loop, this creates
ul_node.append(li_node);
Append thelinode to theulnode (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').append(ul_node);
Finally, once theulis completed, we append it to the element whose id is#seasons
All Together
Complete markup is: