简体   繁体   中英

Javascript alert box using javascript variable and php array

I am trying to print johan using javascript alert box with javascript variable and php array. But following code is not working.

$result['firstName']['lastName']='johan';
$data =  json_encode($result);

?>
<html>
<body onload='myfunction(<?php echo $data; ?>);'>
<script>
function myfunction(data) 
{
  var fn = "firstName";
  alert(data.+fn+.lastName);
}
</script>
</body>
</html>

try alert(data.firstName.lastName);

EDIT:

I just tested this and it works as expected so cheers :)

<?php
$result['firstName']['lastName']='johan';
$data =  json_encode($result);
echo $data;
?>
<html>
<body onload='myfunction(<?php echo $data; ?>);'>
<script>
function myfunction(data) 
{
  var fn = data.firstName;
  alert(fn.lastName);// you can use data.firstName.lastName too 
}
</script>
</body>
</html>

This should do it:

alert(data[fn].lastName);

Because your index is inside a variable, you have to use the brackets.

At least you need to eval your json string generated in php

In you alert use: data[fn].lastName

Mb I missed smth else.

You can't access variable object property using dot notation. You need to use [] instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM