Reputation: 79676
my php code looks like this:
$result['firstName']['lastName']='johan';
echo json_encode($result);
how should i type to use this array in javascript with jquery?
...function(data) {
alert(data.firstName.lastName);
});
or
...function(data) {
alert(data.firstName['lastName']);
});
Upvotes: 1
Views: 2105
Reputation: 1341
JQuery doesn't effect object access, so you can just do
data.firstName.lastName
Upvotes: 4
Reputation:
The object['property'] syntax is only needed in javascript for numbers or syntactically ambiguous keys (e.g. those containing spaces).
Upvotes: 2
Reputation: 4498
Javascript doesn't technically have associative arrays, so technically in Javascript you're working with an Object. Either syntax you used should work.
Upvotes: 2
Reputation: 32878
This worked for me but its very ugly
<?php
$result['firstName']['lastName']='johan';
$data = json_encode($result);
?>
<html>
<body onload='myfunction(<?php echo $data; ?>);'>
<script>
function myfunction(data)
{
alert(data.firstName.lastName);
}
</script>
</body>
</html>
Upvotes: 1