Reputation: 2771
test.php includes this:
echo json_encode( array(
array("name"=>"John","time"=>"2pm"),
array("name"=>"2","time"=>"1242pm"),
array("name"=>"J231ohn","time"=>"2p213m"),
));
jQuery:
$.get("test.php", function(data) {
$.each(data, function(n, val) {
alert(n + ': ' + val)
});
}, "json");
This is the result:
0: [object Object]
1: [object Object]
2: [object Object]
What am I doing wrong?
Upvotes: 2
Views: 8948
Reputation: 11
Use .getJSON. Try:
$.getJSON("test.php", function(data) {
$.each(data, function(n, val) {
alert(n + ': ' + val)
});
});
Upvotes: 1
Reputation: 1835
depending on your browser, you could call val.toSource()
which will spill the objects contents instead of its type (which is the default behaviour for .toString() )
a nice, shorthand way to write this is alert ([n, val.toSource() ]);
Upvotes: 0
Reputation: 846
Use console.log(data) to get a decent look at what's inside your JSON from the console in Firebug or Webkit.
Great tutorial here: http://jqueryfordesigners.com/debugging-tools/
Upvotes: 2
Reputation: 4642
Technically, nothing. 'val' references the object, which I suspect isn't what you want. You probably want the values stored in each array. So, instead of alerting out 'val', you probably want to access the array key values:
alert(n + ': ' + val.name + ' ' + val.time)
Upvotes: 1
Reputation: 40863
I dont know php but my guess is you need to do this instead, as each val is a json object.
$.get("test.php", function(data) {
$.each(data, function(n, val) {
alert(n + ': ' + val.name + ' ' + val.time)
});
}, "json");
jsfiddle example
Upvotes: 2
Reputation: 1039598
Try:
alert(n + ': name = ' + val.name + ' time = ' + val.time);
Upvotes: 5