我使用chart.js在我的页面上生成图表。 但是,我希望这些图表由我的SQL数据库填充。 我可以从我的数据库中获取数据,但我不会绘制图表
我的主页上有一个名为" OmzetChart" ,这是图表的来源。
<script>
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = data;
//alert(JSON.stringify(data));
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
</script>
GetData.php的页面会产生以下结果(这就是我需要的,只是想把它放到我的图表中):
[{"dag":"23","0":"23","uur":"13","1":"13","SomOmzet":"23.00","2":"23.00"},{"dag":"23","0":"23","uur":"18","1":"18","SomOmzet":"2.50","2":"2.50"}]
Getdata.php:
<?php
include ("../PDO.php");
$conn = DatabasePDO::getInstance();
$sql = "SELECT DATEPART(DD, receiptdatetime) as dag ,DATEPART(hh, receiptdatetime) as uur, ISNULL(abs(cast(sum(NetAmount) as decimal (10,2))),0) as SomOmzet FROM ReceiptLine a , Receipt b, ReceiptLineDetail c
where a.LineType = 200 and a.receiptID = b.receiptid and a.receiptlineID = c.receiptlineID
group by DATEPART(DD, receiptdatetime), DATEPART(hh, receiptdatetime)";
$st = $conn->prepare($sql);
$st->execute();
$list = array();
while ( $row = $st->fetch() ) {
$list[] = $row;
}
$conn = null;
echo json_encode( $list );
?>
答案 0 :(得分:2)
json_encode()
生成一个JSON字符串。您需要parse
使用JSON.parse()
才能使用它。
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
success: function (data) {
lineChartData = JSON.parse(data); //parse the data into JSON
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: lineChartData
});
}
});
此外,使用$.ajax()
方法的dataType
参数,您可以将此解析保留为jQuery。
$.ajax({
type: 'POST',
url: 'templates/getdata.php',
dataType: 'json', //tell jQuery to parse received data as JSON before passing it onto successCallback
success: function (data) {
var ctx = document.getElementById("OmzetChart").getContext("2d");
var myLineChart = new Chart(ctx, {
type: 'line',
data: data //jQuery will parse this since dataType is set to json
});
}
});