我有一个问题,我只能加载1 zingchart在我的网页,即使我有2个图表的代码。
代码将只生成最新的图表,在本例中是饼图,而忽略条形图。
下面是我的代码
<?php
//getDBConnect function
require 'dbconnect.php';
//Get ID from form
$id = $_GET['staffid'];
//connect to database
$con = getDBConnect();
if(!mysqli_connect_errno($con)){
$sqlQueryStr =
"SELECT a.ai_Name, r.duration " .
"FROM report AS r, academicinstitution AS a " .
"WHERE r.ai_Id = a.ai_Id ";
$result = mysqli_query($con,$sqlQueryStr);
mysqli_close($con);
} else {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//Get data into array
$emparray = array();
while ($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
//Group array by ai_Name
$grouparray = array();
foreach($emparray as $item)
{
if(!isset($grouparray[$item["ai_Name"]]))
$grouparray[$item["ai_Name"]] = 0;
$grouparray[$item["ai_Name"]] += $item["duration"];
}
?>
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
};
</script>
<script>
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
};
</script>
<div id="chartBar"></div>
<div id="chartPie"></div>
我该怎么办?
这里的问题是您为window.onload
事件分配了两个函数。JavaScript只允许在事件触发时调用一个函数。如果您为它分配了多个函数,则最新的赋值将覆盖之前的赋值。这就是为什么你的饼状图是渲染的,而不是条形图。
解决方案是将两个渲染调用都放在window.onload
回调中。
是这样的:
<script>
var dataBar=[
<?php
foreach($grouparray as $keys => $value){
echo $value. ",";
}
?>];
var dataPie=[
<?php
foreach($grouparray as $keys => $value){
echo '{';
echo '"text":"'.$keys.'","values":['.$value.']';
echo '},';
}
?>];
window.onload=function(){
zingchart.render({
id:'chartBar',
height:400,
width:600,
data:{
"graphset":[
{
"type":"bar",
"title":{"text":"BarChart"},
"series":[
{
"values":dataBar
}
]
}
]
}
});
zingchart.render({
id:'chartPie',
height:400,
width:600,
data:{
"graphset":[
{
"type":"pie",
"title":{"text":"PieChart"},
"series":dataPie
}
]
}
});
}
</script>
我是ZingChart团队的。