javascript - 是否可以在两个不同的 JavaScript block 中使用相同的变量?

标签 javascript php sql web

我正在开发一个必须显示sql View 的网络,所以我用PHP进行查询,但我必须在图表中显示结果,并且我正在尝试使用google geochart。所以基本上我想做的是:

  1. 使用 PHP 从 SQL View 中选择数据。
  2. 将 PHP 中的数据获取到 JavaScript 变量中,以便我可以在图表中使用它。
  3. 获取要放入 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/

相关文章:

javascript - 文本搜索多个位置

javascript - 在没有 UI 的情况下 ionic 裁剪图像

javascript - 根据输入类型数值创建复选框字段

javascript - 如何将多个类名添加到 fullcalendar 事件对象并删除一个指定的类名

php - 缓存云文件列表

sql - SQLite3查询需要很多时间,您将如何处理?

php - 如何捕获MySql错误代码?

php - ORDER BY 时间戳 < 24 小时的记录数量 (MySQL)

sql - 在SQL Server中创建时间间隔

mysql - 从数百万条记录中选择一条记录慢