我正在开发一个必须显示sql View 的网络,所以我用PHP进行查询,但我必须在图表中显示结果,并且我正在尝试使用google geochart。所以基本上我想做的是:
- 使用 PHP 从 SQL View 中选择数据。
- 将 PHP 中的数据获取到 JavaScript 变量中,以便我可以在图表中使用它。
- 获取要放入 Google Chart API 中的 JavaScript 变量的值,以便它显示我想要的内容。
到目前为止,我已经完成了第 1 点和第 2 点(我认为)。但是,当我尝试在代码的另一部分再次使用 javascript 变量时,它没有任何值,因此没有显示数据,我在资源管理器上得到 undefined
。
相关代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<?php
//connections and stuff
$tsql="SELECT count(*) as Qty, ShipCountry FROM [Orders Qry] group by ShipCountry"; // yes, is the Northwind database example
$stmt = sqlsrv_query($conn, $tsql);
if ($stmt === false)
{
FatalError("Failed to query table: ".$tsql);
}
else
{
$json=array();
$i=0;
echo "<script type='text/javascript'> var countries = []; </script>";
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
echo "<script> countries[".$i."]= ". $row['ShipCountry'] .";</script>";
$i=$i+1;
}
//echo "<h1>". $json["ShipCountry"] ."</h1>"; //I was testing, so the problem is not in retrieving the data from the database.
sqlsrv_free_stmt($stmt);
}
?>
<p>
<script type="text/javascript">
document.write(countries[0]);
</script>
</p>
</body>
</html>
最佳答案
您忘记引用$row['ShipCountry'](似乎是一个字符串);
echo "<script> countries[".$i."]= '". $row['ShipCountry'] ."';</script>";
注意新的引号。
关于javascript - 是否可以在两个不同的 JavaScript block 中使用相同的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29581566/