Monday, July 27, 2009

JSON - JavaScript Object Notation

JSON - JavaScript Object Notation

JSON is a lightweight computer data interchange format. It is a text-based, human-readable format for representing simple data structures and associative arrays (called objects).

Server response:

{"books":[{"book":
{
"title":"JavaScript, the Definitive Guide",
"publisher":"O'Reilly",
"author":"David Flanagan",
"cover":"/images/cover_defguide.jpg",
"blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
}
},
{"book":
{
"title":"DOM Scripting",
"publisher":"Friends of Ed",
"author":"Jeremy Keith",
"cover":"/images/cover_domscripting.jpg",
"blurb":"Praesent et diam a ligula facilisis venenatis."
}
},
{"book":
{
"title":"DHTML Utopia: Modern Web Design using JavaScript & DOM",
"publisher":"Sitepoint",
"author":"Stuart Langridge",
"cover":"/images/cover_utopia.jpg",
"blurb":"Lorem ipsum dolor sit amet, consectetuer adipiscing elit."
}
}
]
}





JAVA SCRIPT Processing
function setDataJSON(req)
{
var data = eval('(' + req.responseText + ')');
for (var i=0;i < data.books.length;i++)
{
var x = document.createElement('div');
x.className = 'book';
var y = document.createElement('h3');
y.appendChild(document.createTextNode(data.books[i].book.title));
x.appendChild(y);
var z = document.createElement('p');
z.className = 'moreInfo';
z.appendChild(document.createTextNode('By ' + data.books[i].book.author + ', ' + data.books[i].book.publisher));
x.appendChild(z);
var a = document.createElement('img');
a.src = data.books[i].book.cover;
x.appendChild(a);
var b = document.createElement('p');
b.appendChild(document.createTextNode(data.books[i].book.blurb));
x.appendChild(b);
document.getElementById('writeroot').appendChild(x);
}
}


PHP JSON
string json_encode ( mixed $value [, int $options= 0 ] )
Returns a string containing the JSON representation of value .

No comments:

Post a Comment