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!!
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:
That’s an array, containing a bunch of object literals. To get to the objects, you’ll need something like:
Update:
Here are the guts of this demonstrated on jsFiddle.