javascript - 将 json 数据从 PHP 传递到 javascript - Google 饼图

标签 javascript php mysql google-visualization

我试图在 mysql 查询后将 json 数据从 php 传递到加载 google 图表 api 的 javascript。查询成功,但数据格式似乎不正确。知道我在这里做错了什么吗?我将其保存为 .html 文件,然后通过浏览器打开它。希望应该如此。

< ?php
$DB_hostname = "localhost";
$DB_Name = "root";
$DB_pass = "root";
$tbl_name="tblname"; // Table name 




$con = mysql_connect($DB_Hostname,$DB_Name,$DB_pass) or die(mysql_error());

mysql_select_db("dbname", $con);
$sql="SELECT *  FROM $tbl_name WHERE is86 = 1";
$result=mysql_query($sql);

$count1 = mysql_num_rows($result);


$sql="SELECT *  FROM $tbl_name WHERE is86 = 0";
$result=mysql_query($sql);

$count2 = mysql_num_rows($result);
$data[0] = array("Changes","count1");
$data[1] = array("Apps with IA Architecture",.$count1.);
$data[2] = array("Apps with no IA Architecture",.$count2.); 

$data = json_encode($data);
? >


<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript"  src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

   // Set a callback to run when the Google Visualization API is loaded.
   google.setOnLoadCallback(drawChart);

   function drawChart() {
     var data = new google.visualization.DataTable(<?=$data?>);


    var options = {
        title: 'Architecture Changes',
        is3D: 'true',
        width: 800,
        height: 600
      };

   var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
    chart.draw(data, options);
    }
    </script>
   </head>

   <body>
   <!--Div that will hold the pie chart-->
  <div id="chart_div"></div>
</body>
</html>

最佳答案

对于使用这样的 DataTable 构造函数,您的数据格式不正确,但您应该能够使用 arrayToDataTable 方法:

var data = google.visualization.arrayToDataTable(<?=$data?>);

此外,将 . 添加到数组时,不应在 $count 变量之前和之后包含它们:

$data[0] = array("Changes", "count1");
$data[1] = array("Apps with IA Architecture", $count1);
$data[2] = array("Apps with no IA Architecture", $count2);

关于javascript - 将 json 数据从 PHP 传递到 javascript - Google 饼图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19573924/

相关文章:

javascript - 重构 javascript 以允许在不需要括号且不使用 'get' 的情况下调用函数

javascript - 如何编写项目以防止 DDoS 攻击

php - 如何确定 MySQL UPDATE 是否确实与 WHERE 子句匹配任何行?

PHP & MySQL 空记录

MySQL优先级

javascript - "if (foo) bar();"和 "foo && bar();"之间的区别

php - 未找到默认实体翻译的翻译形式

mysql - 从一个表中选择包含另一个表中一长串单词中的任何单词的行

c# - MySql 异常 : The timeout period elapsed prior to obtaining a connection from the pool

javascript - 使用 Jasmine 测试 DOM 操作