我在控制器中有一个函数来从sql数据库中获取数据。问题是我没有在图表中获取json数据,有人可以解释,为什么?非常感谢
我已经包含了CI,AJAX和Chart所需的所有cdn 这是控制器。
public function get_chart_data(){
$survey_id = $this->session->userdata('get_survey_id');
$count_yes = $this->global_model->select_single('survey_replies',
['survey_id'=>$survey_id,'reply_message'=>'1']);
echo json_encode($count_yes);
}
我想打印该图表
<canvas id="myChart" max-width="300" max-height="300"></canvas>
并在脚本标签中
$(document).ready(function(){
$.ajax({
url:'<?php echo site_url("user/get_chart_data"); ?>',
success:function(response)
{
var data = [];
for (var i = 0; i < response.length; i++) {
data.push(response[i].reply_message);
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Yes", "No"],
datasets: [{
label: '# of Votes',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
});
}
}
});
});
&#13;
答案 0 :(得分:0)
你正在循环不必要的myChart。
试试这个。
$(document).ready(function(){
$.ajax({
url:'<?php echo site_url("user/get_chart_data"); ?>',
success:function(response)
{
var data = [];
for (var i = 0; i < response.length; i++) {
data.push(response[i].reply_message);
}
var ctx = document.getElementById("myChart").getContext('2d');
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: ["Yes", "No"],
datasets: [{
label: '# of Votes',
data: data,
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
],
borderWidth: 2
}]
},
});
}
});
});