2

I've got two pages, test.php which encodes a JSON array, and test.html which I have using $.getJSON to parse the array from the PHP page. Both pages are in the same directory.

test.php:

<?php for ($x=0; $x<10; $x++){ $arr[$x] = array('Value1'=>"$x", 'Value2'=>"$x"); } $y = json_encode($arr); echo $y; ?> 

test.html:

<html> <head> <script type="text/javascript" src="jquery.js"></script> </head> <body> <ul> <script type="text/javascript"> $(document).ready(function(){ $.getJSON('test.php', function(data) { var items = []; $.each(data, function(key, val) { items.push('<li id="' + key + '">' + val + '</li>'); }); $('<ul/>', { 'class': 'my-new-list', html: items.join('') }).appendTo('body'); }); }); </script> </body> </html> 

test.html is not successfully parsing any of the JSON data from test.php. Can anyone tell me why this is? Thanks!!

1
  • have you checked the return data in the console? are you sure it returns something? Commented Mar 3, 2012 at 2:38

1 Answer 1

3

Looks like you are only iterating over the outer array in your JSON string, and not then over each object literal. You JSON looks like this:

[{"Value1":"0","Value2":"0"},{"Value1":"1","Value2":"1"},{"Value1":"2","Value2":"2"},{"Value1":"3","Value2":"3"},{"Value1":"4","Value2":"4"},{"Value1":"5","Value2":"5"},{"Value1":"6","Value2":"6"},{"Value1":"7","Value2":"7"},{"Value1":"8","Value2":"8"},{"Value1":"9","Value2":"9"}] 

That's an array, containing a bunch of object literals. To get to the objects, you'll need something like:

$.getJSON('test.php', function(data) { var items = []; // Iterate first over the outer array $.each(data, function(key, val) { // Then over the properties of each object contained in the array $.each(val, function(innerkey, innerval) { items.push('<li id="' + innerkey + '">' + innerval + '</li>'); }); }); $('<ul/>', { 'class': 'my-new-list', html: items.join('') }).appendTo('body'); }); 

Update:

Here are the guts of this demonstrated on jsFiddle.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.