2017-09-14 94 views
2

我想让莫里斯甜甜圈图和原因不明我得到空白页。我有两个单独的文件,Chart.php包含sql语句,然后是用于显示图表的邮件文件。动态莫里斯甜甜圈图与php的mysql

Chart.php代码

try { $stmt = $db->prepare(" SELECT gender, count(*) as no_of_gender FROM 
members GROUP BY gender ORDER BY memberID ASC "); 
     $stmt->execute(); 
     } 
    catch(PDOException $e) { 
     echo '<p class="bg-danger">'.$e->getMessage().'</p>'; 
     } 

    $data = array(); 

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     $array[] = array(
      'lable' => $row['gender'], 
      'value' => $row['no_of_gender'] 
     ); 
     } 

$data = json_encode($data); 

这里是我用来接收$ DATA Chart.php

<script type="text/javascript" language="javascript" > 

     $(document).ready(function(){ 

     var donut_chart = Morris.Donut({ 
      url :"charts.php", 
      element: 'chart', 
      data: <?php echo $data; ?> 
       }); 
      }) 

    </script> 
+0

你能分享你看到什么样的错误?如果你得到一个空白页面,你的JavaScript控制台说什么?得到的页面的来源是什么? – tristansokol

+0

@tristansokol正在获取未定义变量:数据 –

回答

1

在chart.php文件要在编码空数组JavaScript代码。

更换

$data = json_encode($data); 

$data = json_encode($array); 

,并确保你正确地传递$数据从chart.php文件中的JavaScript代码。

的工作代码如下

<html> 
<head> 
    // if you have downloaded these files to your project, change the path to include them. 
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css"> 
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script> 
    <script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script> 
</head> 
<body> 

<?php 
try { $stmt = $db->prepare(" SELECT gender, count(*) as no_of_gender FROM 
members GROUP BY gender ORDER BY memberID ASC "); 
     $stmt->execute(); 
     } 
    catch(PDOException $e) { 
     echo '<p class="bg-danger">'.$e->getMessage().'</p>'; 
     } 

    $data = array(); // define array 

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) { 
     $data[] = array(
      'lable' => $row['gender'], 
      'value' => $row['no_of_gender'] 
     ); 
     } 

//print_r($data); // to check the array data 
$json_data = json_encode($data); // convert to json array 
?> 
<div id="chart" style="height: 250px;"></div> 

<script type="application/javascript"> 

    Morris.Donut({ 
     element: 'chart', // div id 
     data: <?php echo $json_data; ?>, 
     xkey: 'lable', 
     ykeys: ['value'], 
     labels: ['Value'] 
    }); 

</script> 


</body> 
</html> 
+0

正在获取未定义变量:数据 –

+0

Javascript代码应该位于chart.php文件中。 –

+0

更新答案以包含单个页面中的所有内容。 –