Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can’t get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
JSON is not a programming language, and it’s certainly not executable as PHP. It’s just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any
<?phptags. (Of course, as with HTML, you can also make it a.phpfile and just not have any PHP in it, other than something to set the Content-Type since the file suffix won’t do it automatically. But that’s wasteful.)If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).