簡體   English   中英

使用JSON為數據庫驅動的圖表(highchart.js)獲取圖表的值

[英]Fetch Values for Chart using JSON for Database driven Chart (highchart.js)

我正在使用Codepen中的庫創建一個簡單的數據庫驅動圖:

Highchart.js

我有一個僅顯示圖表的HTML文件,主要數據和處理是通過index.js文件完成的,該文件包含用於繪制圖形的靜態值。 該文件是:

$(function () {
var options = {

    chart: {
        renderTo: 'container'
    },

    subtitle: {
        text: 'Subtitle'
    },

    xAxis: {
        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
      tickInterval: 4
    },

/***  The following Values are needed to be fetched from DB which are now static */ 

    series: [{
        data: [89.9, 21.5, 16.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]

},
chart = new Highcharts.Chart(options);

$('#redraw').click(function() {
    console.log(chart.xAxis[0]);
    chart.redraw();
});
});

現在,我想創建PHP文件,該文件將從數據庫中獲取數據並將其發送到JS文件。

 $test=mysql_query("select id from tbl_graph");
 $rowtest=mysql_fetch_array($test);

現在,我需要從數據庫中獲取的數據需要發送到Index.js文件,以便可以直接從數據庫連接index.js中的以下靜態值。

 series: [{
        data: [89.9, 21.5, 16.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
    }]

我將不勝感激。

答案不是那么直接。 簡單來說,您需要ajax請求來從服務器獲取數據。

這是詳細步驟

  1. 您需要創建php,返回json

     <?php $return_arr = array(); $fetch = mysql_query("SELECT * FROM tbl_graph"); while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) { $row_array[] = $row['value']; array_push($return_arr,$row_array); } echo json_encode($return_arr); // This will return [4,5,6,7] in json ?> 
  2. 更新您的腳本以從php獲取數據

     $(function () { var options = { chart: { renderTo: 'container' }, subtitle: { text: 'Subtitle' }, xAxis: { categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], tickInterval: 4 }, /*** The following Values are needed to be fetched from DB which are now static */ series: [{ data: [89.9, 21.5, 16.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4, 29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] }] }, chart = new Highcharts.Chart(options); $('#redraw').click(function() { // whenever you click redraw, it will grab json from php file above $.getJSON('http://yourpath.com/test.php', function (csv) { chart.series[0].setData(csv,true);//then set data and return csv } }); 

    });

我還沒有測試代碼。 可能您需要弄清楚是否存在語法錯誤。 但希望您能對如何從php獲取json有所了解

在PHP腳本中,您需要准備數組,並通過json_encode()函數轉換為json。 然后,僅需要使用javascript中的$ .getJSON()並在highcharts中使用您的數據。

其他解決方案是在javascript中注入php,如下所示:

http://www.highcharts.com/docs/working-with-data/preprocessing-data-from-a-database/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM