I am trying to print simple JSON data to understand and learn about JSON. I can’t quite figure out what I am doing wrong here.
I am following this tutorial here
http://www.youtube.com/watch?v=rncW-74VL7U
This is my JavaScript:
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$.getJSON("json.php", function(data)
{
//json.php get the JSON data from here
//function(data) callback function
var itemslist = data.items[0];
document.write(itemslist.key);
});
</script>
Here is the PHP
<?php
// Set up the PHP to return the data in JSON format
header("content-type: application/json; charset=UTF-8" );
// This is a array of objects [key:"value", key2 : {k:"val", k2:"val2"}]
$myobj = '{items : [key:"value", key2 : {k:"val", k2:"val2"}]}';
$count = 2;
// Encode the above variables in JSON
echo json_encode(array("items" => $myobj, "count" => $count));
Help is much appreciated…
First, your json had two items nodes in it. The items in the json_encode and the items in the myobj string (now array). This is why data.items[0] wasn’t working, it needed to be data.items.items[0]. That said, what I first sent you was using keys not indexes so it really needed to be data.items.items.key. All of that said, the current structure I’ve included should be better.
Second, try using console.debug more. I just copied your code on my dev box and ran it and found out most of the json issues by seeing what the object looked like (I’ve included the current console.debug(data) output in the comments to the javascript). Here is a link to info about chromes debug: https://developers.google.com/chrome-developer-tools/docs/console
PHP
Javascript