dp709369831 2018-07-05 18:14
浏览 83
已采纳

没有显示同一页面上的JSON数据的chart.js

Hello I am having a slight issue rendering a chart using chart.js,pulling data from a mysql db, It works when I am using an external file, to pull the data, However I am trying to code the entire thing on one File, but this is giving some trouble I am assuming the json_encode data is not being supplied properly the code is listed below:

<!DOCTYPE html>
<html>
<head>
<title>Demo Charts</title>  
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="js/jquery.min.js"></script>
    <script type="text/javascript" src="js/Chart.min.js"></script>
    <script src="js/jquery-ui.min.js"></script>
</head>
<body>
    <div>
<?php
$conn = mysqli_connect("localhost","root","password","db1");

$sqlQuery = "SELECT student_id,student_name,marks FROM tbl_marks ORDER BY student_id";
$result = mysqli_query($conn,$sqlQuery);
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}
mysqli_close($conn);
$json = json_encode($data);
?>
        <div>
            <span><h3>Pie Chart</h3></span>
            <canvas id="pieCanvas"></canvas>
        </div>
        <script type="text/javascript"> 
        $(document).ready(function () {
            showGraph2();
        });

        function showGraph2()
        {
            {
                var data = <?php echo $json; ?>;
               // $.post("api/data.php", `==>>THIS WORKS`
             $.post(data,
                function(data)
                {
                    console.log(data);
                     var name = [];
                    var marks = [];
                    var coloR = [];

                     var dynamicColors = function() {
                    var r = Math.floor(Math.random() * 255);
                    var g = Math.floor(Math.random() * 255);
                    var b = Math.floor(Math.random() * 255);
                    return "rgb(" + r + "," + g + "," + b + ")";
                 };


                    for (var i in data) {
                        name.push(data[i].student_name);
                        marks.push(data[i].marks);
                         coloR.push(dynamicColors());
                    }

                    var chartdata = {
                        labels: name,
                        datasets: [
                            {
                                label: 'Student Marks',
                                backgroundColor: '#49e2ff',
                                //borderColor: '#46d5f1',
                                backgroundColor: coloR,
                                hoverBackgroundColor: '#CCCCCC',
                                hoverBorderColor: '#666666',
                                data: marks
                            }
                        ]
                    };

                    var graphTarget = $("#pieCanvas");

                    var barGraph = new Chart(graphTarget, {
                        type: 'pie',
                        data: chartdata
                    });
                });
            }
        } 
         showGraph2();


</script>

    </div> 

</body>
</html>
  • 写回答

1条回答 默认 最新

  • drbxr86044 2018-07-05 18:55
    关注

    Here's the relevant JavaScript part:

    const useAJAX = false;
    
    $(document).ready(function () {
      if (useAJAX) $.getJSON('api/data.php').then(showGraph);
      else showGraph(<?= $json ?>);
    });
    
    function showGraph(data) {
      console.log(data);
      var name = [];
      var marks = [];
      var coloR = [];
      // etc, etc
    }
    

    I have completely separated a) obtaining the data and b) processing the data. This way you can nicely switch between the two.

    I have directly inserted the JSON into the script, like you did. Not super clean or good practice, but will work fine for now.

    I have rewritten the AJAX part slightly, I'm using $.getJSON instead, assuming that the file doesn't require any POST parameters anyway. And I used .then(), taking advantage of the fact that jQuery AJAX methods return Promises.

    Final tip: don't mix PHP and HTML/JS like that. Move all your PHP stuff to the very top, set all your variables before your first echo / plain text. Then use ?><!DOCTYPE html> to move to HTML.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动