Javascript and JSON Together Forever

I created a static website recently for my sister. It is hosted on our ISP’s server, which means there is no way to do any server-side coding. The site is coding in html with a few pages using javascript and JSON (javascript object notation). Just what is JSON you ask? It is simply a way of structuring data like the more commonly known XML format, but it’s easier to use with javascript.

Why not just code the site in straight html? Well, I wanted the website to be somewhat easily modifiable. Even if the JSON is embedded in the page, it still allows easier access to the content and also cuts down on the actual number of pages.

For example, there is a page that displays a list of graphic designs she has made. The JSON text is processed when the page loads. When one of the graphic design links are clicked, a javascript function modifies the html on the page to display the new picture/title/description.

An example of JSON and the eval() function:

var pageInformation = '{"collection":[
   {"filename":"butterflyanimation.gif",
       "title":"Butterfly GIF",
 "description":"An animated butterfly made in ImageReady and Illustrator"},
   {"filename":"butterflypana.jpg",
       "title":"Express Colors",
 "description":"Express Inspiration for Spring 2005 Colors."}]}';

// create an object from the JSON formatted data
var objItems = eval('(' + pageInformation ')');

If this code were in a script tag, what would happen? The variable objItems would store all of that data in pageInformation as a javascript object. That means we can now access the data like: objItems.collection[0].title, which would be “Butterfly GIF”.

To change an element in a webpage, make sure it has its “id” property set. after that use the javascript:

document.getElementById('id_name').innerHTML = 'whatever';

Posted

in

,

by