views:

78

answers:

4

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']);
});
+3  A: 

JQuery doesn't affect object access, so you can just do

data.firstName.lastName
tmpvar
In my case after echo the $data i got an alert johan :-)
streetparade
what do you mean with "doesn't affect object access"
weng
@noname, I was just saying that introducing jQuery doesn't change the situation.
tmpvar
+1  A: 

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>
streetparade
+1  A: 

Javascript doesn't technically have associative arrays, so technically in Javascript you're working with an Object. Either syntax you used should work.

Pickle
Technically, every instance of Object is an associative array.
Anonymous
+1  A: 

The object['property'] syntax is only needed in javascript for numbers or syntactically ambiguous keys (e.g. those containing spaces).

bluej100