【问题标题】:Highcharts Dynamic Chart with MySQL Data doesn't reload带有 MySQL 数据的 Highcharts 动态图表不会重新加载
【发布时间】:2014-03-18 23:33:06
【问题描述】:

大家晚上好,

此时我尝试使用 HighChart / HighStock,几周后我能够在图表中显示我的 MySQL 数据。但是:我总是想要更多。

好吧,我尝试制作一个动态图表,就像您可能从网站上知道的示例一样令人耳目一新。 http://jsfiddle.net/sdorzak/HsWF2/

我使用示例代码作为指导。它不起作用,但认为问题在于缺少 y 轴,因为 y 轴数据来自我的 MySQL 数据库,而 x 轴应该是当前时间。

  <!DOCTYPE HTML>
  <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>POS RESULT</title>

    <script type="text/javascript"   src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script src="http://code.highcharts.com/highcharts.js"></script>
    <script src="http://code.highcharts.com/modules/exporting.js"></script>

</head>

        <body>

    <?php
include "config.php";

$SQL1 =     "SELECT * FROM Prices WHERE ticker ='FB'";

$result1 = mysql_query($SQL1);
$data1 = array();
while ($row = mysql_fetch_array($result1)) {
   $data1[] = $row['Close'];
}


?>

<script type="text/javascript">
$(function () {
    var chart;
    $(document).ready(function() {
        chart = new Highcharts.Chart({
            chart: {
                renderTo: 'container',
                type: 'line',
                marginRight: 130,
                marginBottom: 25,
                events: {
                  load: function() 
                  {

                     var series = this.series[0];
                     setInterval(function() {
                     var x = (new Date()).getTime();
                     series.addPoint([x], true);
                  }, 1000);
            },
            title: {
                text: 'Monthly Average Temperature',
                x: -20 //center
            },
            subtitle: {
                text: 'Source: WorldClimate.com',
                x: -20
            },
            xAxis: {
                                type: 'datetime',
                tickPixelInterval: 150

                //categories: [<?php echo join(',', $data2); ?>],
            },
            yAxis: {
                title: {
                    text: 'Temperature (°C)'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function() {
                        return '<b>'+ this.series.name +'</b><br/>'+
                        this.x +': '+ this.y +'°C';
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'top',
                x: -10,
                y: 100,
                borderWidth: 0
            },
            series: [{
                name: 'Tokyo',
                data: [<?php echo join(',', $data1);  ?>]
            }]
        });
    });

});
    </script>

<div id="container" style="min-width: 500px; height: 400px; margin: 0 auto"></div>

</body>
   </html>

我正在谈论的以及示例中显示的段落是

    chart: {
        renderTo: 'container',
        type: 'spline',
        marginRight: 10,
        events: {
            load: function() {

                // set up the updating of the chart each second
                var series = this.series[0];
                setInterval(function() {
                    var x = (new Date()).getTime(), // current time
                        y = Math.random();
                    series.addPoint([x, y], true, true);
                }, 1000);
            }
        }

但是,正如我已经写过的,我不需要随机的 y 轴,只需要 x 轴。

也许你可以帮忙。 感谢您的帮助。

编辑: live-server-data.php

<?php
// Set the JSON header
header("Content-type: text/json");


include "config.php";

$SQL1 =     "SELECT * FROM Prices WHERE Ticker ='TSLA'";

$result1 = mysql_query($SQL1);

while ($row = mysql_fetch_array($result1)) {
   $data1[] = $row['Close'];
}

// The x value is the current JavaScript time, which is the Unix time multiplied 
// by 1000.
$x = time() * 1000;
// The y value is a random number
$y = $data1;

// Create a PHP array and echo it as JSON
$ret = array($x, $y);
echo json_encode($ret);
?>

“关闭”的值是十进制的 24,4。

【问题讨论】:

    标签: javascript mysql charts highcharts


    【解决方案1】:

    查看该解决方案:http://www.highcharts.com/studies/live-server.htm

        var chart; // global
    
        /**
         * Request data from the server, add it to the graph and set a timeout to request again
         */
        function requestData() {
            $.ajax({
                url: 'live-server-data.php', 
                success: function(point) {
                    var series = chart.series[0],
                        shift = series.data.length > 20; // shift if the series is longer than 20
    
                    // add the point
                    chart.series[0].addPoint(eval(point), true, shift);
    
                    // call it again after one second
                    setTimeout(requestData, 1000);  
                },
                cache: false
            });
        }
    
        $(document).ready(function() {
            chart = new Highcharts.Chart({
                chart: {
                    renderTo: 'container',
                    defaultSeriesType: 'spline',
                    events: {
                        load: requestData
                    }
                },
                title: {
                    text: 'Live random data'
                },
                xAxis: {
                    type: 'datetime',
                    tickPixelInterval: 150,
                    maxZoom: 20 * 1000
                },
                yAxis: {
                    minPadding: 0.2,
                    maxPadding: 0.2,
                    title: {
                        text: 'Value',
                        margin: 80
                    }
                },
                series: [{
                    name: 'Random data',
                    data: []
                }]
            });     
        });
    

    【讨论】:

    • 认为我接近正确的结果。现在它显示没有线条的图表。在 live-server-data.php 我替换了 rand(0, 100);与 $data1;对于我从表中获得的数据。但它没有显示任何内容,也没有显示任何新的表格条目。你对此有什么想法吗?
    • 一点也不。但我猜测 $data1 的格式不正确 - 应该是数字。你在 javascript 控制台中有什么错误?
    • $data1 正在从 Close 获取数据,它是十进制的 24,4。我从上面的 live-server-data.php 添加了代码。至于 javascript 控制台:Firebug 不报告任何错误或警告。这将证实您的猜测。
    • 我明白了,那么我们需要更多信息,你能在// add the point 行之前添加console.log(point) 吗?然后告诉我你在 JS 控制台/firebug 中有什么。
    • 谢谢你,帕维尔。现在我知道我要寻找什么了。非常感谢!你摇滚!
    【解决方案2】:

    我正在尝试创建另一个可以与我的条形图相关的页面。你可以通过他的代码。它对我有用

    <!DOCTYPE html>
    <html>
       <head>
          <?php
             session_start();
    
    
             ?>
          <meta charset="utf-8">
          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
          <script src="http://code.highcharts.com/highcharts.js"></script>
          <script src="http://code.highcharts.com/modules/exporting.js"></script>
          <script>
             $('#calendar').datepicker({
             });
    
             !function ($) {
               $(document).on("click","ul.nav li.parent > a > span.icon", function(){          
                 $(this).find('em:first').toggleClass("glyphicon-minus");      
               }); 
               $(".sidebar span.icon").find('em:first').addClass("glyphicon-plus");
             }(window.jQuery);
    
             $(window).on('resize', function () {
               if ($(window).width() > 768) $('#sidebar-collapse').collapse('show')
             })
             $(window).on('resize', function () {
               if ($(window).width() <= 767) $('#sidebar-collapse').collapse('hide')
             })
          </script> 
          <style>
             .selection{
             border: 1px solid gray;
             border-radius: 10px;
             padding: 10px;
             text-decoration:none;
             float:left;
             margin:4px;
             text-align:center;
             display: block;
             color: green;
             }
             .page-header{
             text-align:center;
             text-decoration:hover;
             color: blue;
             font-size: 30px;
             }
          </style>
          <script>
             $(function () {
    
                 //on page load  
                 getAjaxData(1);
    
                 //on changing select option
                 $('#dynamic_data').change(function(){
                   var val = $('#dynamic_data').val();
                   getAjaxData(val);
                 });
    
                 function getAjaxData(id){
    
                 //use getJSON to get the dynamic data via AJAX call
                 $.getJSON('datab1.php', {id: id}, function(chartData) {
                   $('#container').highcharts({
                     chart: {
                       type: 'column'
                     },
                     title: {
                       text: 'Analysis of Data Type in The World'
                     },
                     xAxis: {
                     categories: ['Population', 'Health', 'Agriculture', 'Development', 'Transport', 'Education', 'Social', 'Tourism', 'Finance','Business','Economy', 'Industry', 'Employment', 'Weather', 'Food', 'Energy', 'Infrastructure', 'Science&Technology', 'Government','Culture', 'Religion',
                     'Justice&Law', 'Country', 'Water Resource', 'Maritim', 'Military', 'International', 'Geography', 'Statistics', 'Others','Electronic','Biotechnology', 'Women', 'Gender', 'Cartography','Disability','Position','Marital','CDF','Research']
    
                     },
                     yAxis: {
                       min: 0,
    
                       title: {
                         text: 'Percentage (%)'
                       }
                     },
                     legend: {
                   enabled: false
                 },
                 tooltip: {
                   headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                   pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                     '<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
                   footerFormat: '</table>',
                   shared: true,
                   useHTML: true
                 },
                 plotOptions: {
                   column: {
                     pointPadding: 0.2,
                     borderWidth: 0
                   }
                 },
                     series: chartData
    
                   });
    
                 });
               }
             });
          </script>
       </head>
       <body class="hold-transition skin-blue sidebar-mini">
          <div id="container" style="width: 100%; min-height: 500px; margin: 0 auto"></div>
       </body>
    </html>
    

    这是从 mysql 获取数据的代码

    <?php
    require('dbcon.php');
    
    //select database
    
    
    
    //define array
    //we need two arrays - "male" and "female" so $arr and $arr1 respectively!
    $arr    = array();
    $result = array();
    
    //get the result from the table "highcharts_data"
    $sql = "select * from world";
    $q = mysqli_query($con, $sql) or die(mysqli_error());
    $j = 0;
    while ($row = mysqli_fetch_assoc($q)) {
    
        //highcharts needs name, but only once, so give a IF condition
        if ($j == 0) {
            $arr['name'] = 'Percentage';
    
            $j++;
        }
        //and the data for male and female is here
        $arr['data'][] = $row['datavalue'];
    
    
    }
    
    //after get the data for male and female, push both of them to an another array called result
    array_push($result, $arr); //1
    
    
    //now create the json result using "json_encode"
    print json_encode($result, JSON_NUMERIC_CHECK);
    
    mysqli_close($con);
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-02
      • 2011-05-11
      • 1970-01-01
      • 1970-01-01
      • 2016-06-08
      • 1970-01-01
      • 2014-03-31
      • 2016-03-06
      相关资源
      最近更新 更多