Using JSON with PHP : an example

__________________________________________
index.php
______________________________________________

$array = array
(
["books"] => array(
["0"] => array
(
["book"] => array
(
["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."
)

)

["1"] => array
(
["book"] => array
(
["title"] => "DOM Scripting"
["publisher"] => "Friends of Ed"
["author"] => "Jeremy Keith"
["cover"] => "/images/cover_domscripting.jpg"
["blurb"] => "Praesent et diam a ligula facilisis venenatis."
)

)

["2"] => array
(
["book"] => array
(
["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."
)

)

)

)
die(json_encode($array));

______________________________________
index.js
______________________________________
window.onload = xmlHttp;

function xmlHttp()
{
if (window.XMLHttpRequest){xmlhttp = new XMLHttpRequest();}
else if (window.ActiveXObject){xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
else alert("XMLHttpRequest & ActiveXObject not active");
xmlhttp.open('POST', "index.php", true);
xmlhttp.onreadystatechange = function(){if(xmlhttp.readyState == 4 && xmlhttp.status == 200)setDataJSON(eval('(' + xmlhttp.responseText + ')'));}
xmlhttp.send(r);
}

function setDataJSON(req)
{
var data = eval('(' + req.responseText + ')');
for (var i=0;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('DivIdWhereChangeWillShown').appendChild(x);
}
}



Post a Comment