doujiang1913 2017-04-07 08:35
浏览 182

雷达图(chart.js 2.5.0)使用数据库值创建第二层

I'm using Chartjs to create a radar chart to show scores of modules. It is working for 1 module however when I enter a 2nd module the data is placed in the same dataset causing the labels to double. The value points are also not changing name keeping the first modules point label but having different values.

This is the function used to create the graph, if the data is undefined it creates a chart but if not it adds the data to the dataset.

<script src=//code.jquery.com/jquery-3.2.1.min.js></script>
<script src=https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.bundle.js></script>
<input id=MOD_CODE value=SET08108><button id='go'>Go</button>

<canvas id="myChart" width="300" height="300"></canvas>
<script>
var data;
$(function(){
  $('#go').click(function(){
    $.ajax({url:'output.php', data 
      {MOD_CODE:$('#MOD_CODE').val()},dataType:'json', success:function(d){
    if(data===undefined)
      data = {labels:[],datasets:[{label:$('#MOD_CODE').val()+' Results',data:[],}]};
  else
  {
    data.datasets.push({label:$('#MOD_CODE').val()+' Results',data:[],});   
  }
  for(var i=0;i<d.length;i++){
    data.labels.push(d[i][0]);
    data.datasets[0].data.push(parseFloat(d[i][1]));
  }
  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, {
     type: 'radar',
     data:data,
     options:{
       responsive:false,
       scale:{ticks:{beginAtZero: true}}}});
    }});
  })
});
</script>

This is the the php file which gets the data based on the module code from the database, it also converts to json format for the dataset.

<?php
if(!array_key_exists('MOD_CODE',$_REQUEST)){
  print "<form><input name=MOD_CODE></form>";
  exit();
}

$con = new mysqli('');
  if (mysqli_connect_errno()) {
  printf("Connection failed: %s
", mysqli_connect_error());
  exit();
}
$sql = " SELECT QUE_CODE,
         100*AVG(CASE WHEN RES_VALU IN (4,5) THEN 1 ELSE 0 END) AS v
         FROM INS_RES
         WHERE MOD_CODE = ?
         GROUP BY QUE_CODE
         ORDER BY QUE_CODE
       ";
$stmt = $con->prepare($sql)
  or die($con->error);
$stmt->bind_param('s',$_REQUEST['MOD_CODE'])
  or die('Bind error');
$stmt->execute();
$res = $stmt->get_result()
  or die('get_result failed: '.$con->error);
print json_encode($res->fetch_all());
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 关于大棚监测的pcb板设计
    • ¥15 stm32开发clion时遇到的编译问题
    • ¥15 lna设计 源简并电感型共源放大器
    • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
    • ¥15 Vue3地图和异步函数使用
    • ¥15 C++ yoloV5改写遇到的问题
    • ¥20 win11修改中文用户名路径
    • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
    • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
    • ¥15 帮我写一个c++工程