同一页面上带有JSON数据的chart.js不显示 [英] chart.js with JSON Data on Same page not displaying

查看:57
本文介绍了同一页面上带有JSON数据的chart.js不显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用chart.js绘制图表并从MySQL数据库中提取数据时遇到了一个小问题.当我使用外部文件提取数据时,它可以工作,但是我试图将整个文件编码到一个文件上,但这给我带来麻烦,我假设 json_encode 数据不在正确提供的代码如下:

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>

推荐答案

以下是相关的JavaScript部分:

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
}

我已经完全分离了a)获取数据和b)处理数据.这样,您就可以在两者之间很好地切换.

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

我已经像您一样将JSON直接插入脚本中.这不是超级干净或好的做法,但暂时可以正常工作.

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

我已经稍微重写了AJAX部分,我改用 $.getJSON ,假设该文件仍然不需要任何POST参数.我使用了 .then(),利用了jQuery AJAX方法返回

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.

最后的提示:不要像这样混合使用PHP和HTML/JS.将所有PHP内容移到最顶部,在第一个echo/纯文本之前设置所有变量.然后使用?><!DOCTYPE html> 移至HTML.

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.

这篇关于同一页面上带有JSON数据的chart.js不显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆