这是我从mysql中获取数据,然后将数据值导入morrisjs的简单代码,但我的页面完全是空白的,没有显示任何内容。我是这个的新手
<?php
$conn=mysqli_connect("localhost","root","","userchart");
$query= "SELECT * FROM chart";
$result=mysqli_query($conn,$query);
$chart_data='';
while($row=mysqli_fetch_array($result))
{
$time= strtotime($row['time']);
$chart_data .="{ user:'".$row['uid']."', time:".date('i',$time)."}";
}
echo $chart_data = substr($chart_data, 0, -1);
?>
我用这句话来测试我是否得到了正确格式的值,以及格式是否正确,但最后没有显示折线图。
echo $chart_data = substr($chart_data, 0, -1);
<html>
<head>
<title> CHART USING MORRIS.JS</title>
<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>
<div id="chart" style ="height 250px;"></div>
<script>
new Morris.Line({
// ID of the element in which to draw the chart.
element: 'chart',
// Chart data records -- each entry in this array corresponds to a point on
// the chart.
data: [<?php echo $chart_data; ?>],
// The name of the data record attribute that contains x-values.
xkey: 'user',
// A list of names of data record attributes that contain y-values.
ykeys: ['time'],
// Labels for the ykeys -- will be displayed when you hover over the
// chart.
labels: ['time']
});
</script>
</body>
</html>
未经测试,但您可能会尝试这样做。与其进行一些松散的字符串操作,不如使用json_encode
<?php
$conn=mysqli_connect("localhost","root","","userchart");
$query= "SELECT * FROM chart";
$result=mysqli_query($conn,$query);
$data=array();
while( $row=mysqli_fetch_array($result) ){
$data[]=array(
'user' => $row['uid'],
'time' => date('i',strtotime( $row['time']) )
);
}
$json=json_encode( $data );
?>
<html>
<head>
<title>CHART USING MORRIS.JS</title>
<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>
<div id="chart" style ="height 250px;"></div>
<script>
<?php
printf('var json=%s;',$json);
?>
new Morris.Line({
element: 'chart',
data:json,
xkey:'user',
ykeys:['time'],
labels:['time']
});
</script>
</body>
</html>