I'm trying to use a JSON array generated in a php function in a javascript function. My code is this:
$query = "SELECT lat, lng FROM Eventi";
$result = mysql_query($query) or die(mysql_error() . "<br/><br/>" . $query);
if (mysql_affected_rows() != 0) {
while($r = mysql_fetch_array($result)) {
$rows = array(
"latitudine" => $r['lat'],
"longitudine" => $r['lng'],
);}
$risultato_rows = json_encode($rows);
Now I want to recover them in a subroutine did javascript to use them, and I tried so:
var res = JSON.parse($risultato_rows);
alert var prova = res.[latitudine];
This code doesn't work; what can I do to make it function properly?
res.[latitudine]; // You seem to mix up both the
// dot and bracket notation..
supposed to be either
res.latitudine;
OR res["latitudine"];
A PHP variable isn't directly visible in Javascript. Supposing you're not doing AJAX but just trying to embedd JSON in your script, you might do this :
?><script>
var res = JSON.parse('<?php echo $risultato_rows; ?>');
var prova = res.latitudine;
alert (prova);
</script><?php
There are a few problems with your code:
You need to echo
the JSON string that is contained in $risultato_rows
. That is:
var res = JSON.parse('<?= $risultato_rows; ?>');
When accessing properties, you put the key name as a string in the brackets. To access the latitudine
property, you would use res.["latitudine"]
prova
and alert it.
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.