在AmCharts中显示数据库中的数据

时间:2016-11-16 12:03:49

标签: mysql json charts amcharts

我正在尝试使用AmCharts制作图表并在其网站上关注此示例:https://www.amcharts.com/kbase/using-data-loader-to-connect-charts-to-mysql-data-base/

我的原始代码是

var chart = AmCharts.makeChart("chart_1", {
        "pathToImages": App.getGlobalPluginsPath() + "amcharts/amcharts/images/",

        "dataProvider": [{
            "year": 2009,
            "income": 23.5,
            "expenses": 18.1
        }, {
            "year": 2010,
            "income": 26.2,
            "expenses": 22.8
        }],
            // bunch of graph stylings
    });

    $('#chart_1').closest('.portlet').find('.fullscreen').click(function() {
        chart.invalidateSize();
    });
}

我尝试从mysql加载数据

var chart = AmCharts.makeChart("chart_1", {
    "type": "serial",
    "dataProvider": {
        "url": "data.php"
    },
        "pathToImages": App.getGlobalPluginsPath() + "amcharts/amcharts/images/",

      // bunch on graphs style

    });

    $('#chart_1').closest('.portlet').find('.fullscreen').click(function() {
        chart.invalidateSize();
    });
}

包含硬编码数据的原始代码正在运行。下面用mysql不起作用。它是空白页面,不显示图表。控制台上也没有错误。

data.php也在工作并返回json数组。

有人可以帮忙吗?

如果还需要php部分

$query = "
       SELECT *
       FROM my_chart_data
       ORDER BY category ASC";
$result = $link->query( $query );

// All good?
if ( !$result ) {
  // Nope
  $message  = 'Invalid query: ' . $link->error . "n";
  $message .= 'Whole query: ' . $query;
  die( $message );
}


// Set proper HTTP response headers
header( 'Content-Type: application/json' );

// Print out rows
$data = array();
while ( $row = $result->fetch_assoc() ) {
  $data[] = $row;
}
echo json_encode( $data );

1 个答案:

答案 0 :(得分:5)

dataProvider没有网址 - 如果您使用的是dataLoader插件,则需要将其更改为dataLoader。要使用dataLoader插件,首先需要包含插件以及其他图表库,如下所示:

<!-- chart libraries -->
<script type="text/javascript" src="//www.amcharts.com/lib/3/amcharts.js"></script>
<script type="text/javascript" src="//www.amcharts.com/lib/3/serial.js"></script>
<!-- include dataloader -->
<script type="text/javascript" src="//www.amcharts.com/lib/3/plugins/dataloader/dataloader.min.js"></script>

然后将dataProvider更改为dataLoaderdataLoader需要url

var chart = AmCharts.makeChart("chart_1", {
    "type": "serial",
    "dataLoader": {
        "url": "data.php"
    },
    // ...
});

可以在github页面here上找到完整的dataloader文档。