我正在尝试在我的项目中制作一个饼图但我在从数据库中获取数据时遇到问题。我目前正在使用带有内置chart.js的codeigniter和bootstrap模板。
这是我的图表: charts
控制器:
public function loadViewExamResult($exam_no){
$this->load->model('exam_model');
$this->insertChartData($exam_no);
$data = $this->exam_model->loadChartData($exam_no);
echo json_encode($data);
$this->load->view('exam_report_chart', $data);
}
public function insertChartData($exam_no){
$this->load->model('exam_model');
$pass = $this->exam_model->passedScore($exam_no);
echo($pass);
$fail = $this->exam_model->failedScore($exam_no);
echo($fail);
$this->exam_model->insertPieData($exam_no,$pass,$fail);
}
型号:
public function loadChartData($exam_no){
$query = $this->db->query("SELECT passed, failed FROM chart where exam_no = '$exam_no';");
if($query->num_rows() > 0){
return $query->result();
}
else{
return false;
}
}
查看(摘录):
<?php
if($exams != NULL){
foreach($exams as $row){
echo '<tr>';
echo '<td>'.$row->course_code.' '.$row->section.'</td>';
echo '<td>'.$row->exam_desc.'</td>';
echo '<td>'.$row->exam_date.'</td>';
echo '<td>'.$row->duration.'</td>';
echo '<td>'.$row->total_items.'</td>';
echo '<td>'.$row->total_score.'</td>';
echo '<td> <div class="btn-group"> <a class="btn btn-success" onclick = "editExam('.$row->exam_no.')"><i class="icon_pencil-edit"></i></a> <a class="btn btn-danger" onclick = "deleteExam('.$row->exam_no.')"><i class="icon_close_alt2"></i></a> <a class="btn btn-primary" onclick="addExamKey('.$row->exam_no.')"><i class="icon_cloud-download"></i></a> <a class="btn btn-default" role="button" onclick = "viewExamResult('.$row->exam_no.')"> View Result </a> </div> </td>';
echo '</tr>';
}
}
?>
<script language="javascript">
function viewExamResult($exam_no){
$("#main-content").load("loadViewExamResult/" +$exam_no +"/").hide(500).fadeIn();
}
</script>
以下是已经在引导程序模板中的chart.js文件,您只需根据您的数据对其进行自定义。我已经编辑了它,我认为我在JSON部分遇到了问题,这就是为什么饼图没有显示出来的原因。有人可以帮我弄这个吗?我实际上对JSON和javascript知之甚少。请帮我。
chart.js之
$(document).ready(function() {
var numpassed =[];
var numfailed =[];
$.post("<?php echo base_url(). ;?>",
function(data){
var obj = JSON.parse(data);
$.each(obj,function(i,item){
numpassed.push(item.passed);
numfailed.push(item.failed);
});
var doughnutData = [
{
value: numpassed,
color:"#F7464A"
},
{
value : numfailed,
color : "#46BFBD"
},
];
});
new Chart(document.getElementById("doughnut").getContext("2d")).Doughnut(doughnutData);
});
答案 0 :(得分:0)
现在,您正在尝试创建图表而不等待您的回复后数据。将图表创建代码移动到$ .post回调中,如下所示:
$.post("<?php echo base_url(). ;?>",
function(data){
var obj = JSON.parse(data);
$.each(obj,function(i,item){
numpassed.push(item.passed);
numfailed.push(item.failed);
});
var doughnutData = [
{
value: numpassed,
color:"#F7464A"
},
{
value : numfailed,
color : "#46BFBD"
},
];
new Chart(document.getElementById("doughnut").getContext("2d")).Doughnut(doughnutData);
});