Dec 15, 2011
Displaying JSON values with JavaScript : Basics of JSON Template with JavaScript
Today morning I came through the knockout.js. I liked the idea of JSON Templating. You can read more about JSON Template in this post - "Introducing JSON Template".I love JSON, because its light weighted and you can parse it easily any programming language. I wrote a simple prototype to display JSON data in HTML using JavaScript Template. I hope it will help you to understand the mechanism.
I took an example of Facebook graph API to show user information. In this template you can change the data attribute of the element to show the key value from JSON object returned from API.
Here is the code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<meta charset=utf-8 /> | |
<title>Displaying JSON values with JavaScript : Basics of JSON Templating with JavaScript</title> | |
<!--[if IE]> | |
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> | |
<![endif]--> | |
<style> | |
article, aside, figure, footer, header, hgroup, | |
menu, nav, section { display: block; } | |
</style> | |
<script> | |
function loadJSON(url){ | |
var headID = document.getElementsByTagName("head")[0]; | |
var newScript = document.createElement('script'); | |
newScript.type = 'text/javascript'; | |
newScript.src = url; | |
headID.appendChild(newScript); | |
} | |
function show(obj){ | |
var elems = document.getElementsByTagName("span"); | |
for(i=0; i<=elems.length; i++){ | |
var bind = elems[i].getAttribute("data"); | |
if(bind && obj[bind]){ | |
elems[i].innerHTML = obj[bind]; | |
} | |
} | |
} | |
loadJSON('https://graph.facebook.com/motyar&callback=show'); | |
</script> | |
</head> | |
<body> | |
<p>ID: <span data="id"></span></p> | |
<p>Name: <span data="name"></span></p> | |
<p>link: <span data="link"></span></p> | |
<a href="" ></a> | |
</body> | |
</html> |
You can see the working demo here.
I am on twitter @motyar.
Labels: api, json, Tip, Tutorials, Web-service
By : Motyar+ @motyar