[英]How can I use a JSON array generated in PHP in a javascript function?
I'm trying to use a JSON array generated in a php function in a javascript function. 我正在尝试使用javascript函数中的php函数生成的JSON数组。 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"];
或 res["latitudine"];
A PHP variable isn't directly visible in Javascript. PHP变量在Javascript中不直接可见。 Supposing you're not doing AJAX but just trying to embedd JSON in your script, you might do this : 假设您不执行AJAX,而只是尝试将JSON嵌入脚本中,则可以执行以下操作:
?><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
. 您需要echo
显$risultato_rows
包含的JSON字符串。 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"]
要访问latitudine
属性,您可以使用res.["latitudine"]
prova
and alert it. 使用单独的语句将值分配给prova
并对其发出警报。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.