gpt4 book ai didi

javascript - 在图表中显示 mysql 数据库中的数据

转载 作者:行者123 更新时间:2023-11-29 22:17:00 25 4
gpt4 key购买 nike

我正在使用 AmCharts 创建饼图。
我正在尝试将 mysql 数据库中的数据分配给变量 chartData具有字段countryliters。如何将我的 mysql 数据分配给 chartdata

 <script>
var chart;
var legend;



var chartData = [{
"country": "Czech Republic",
"litres": 156.9
},
{
"country": "Ireland",
"litres": 131.1
},
{
"country": "Germany",
"litres": 115.8
},
{
"country": "Australia",
"litres": 109.9
},
{
"country": "Austria",
"litres": 108.3
},
{
"country": "UK",
"litres": 65
},
{
"country": "Belgium",
"litres": 50
}
];

AmCharts.ready(function () {
// PIE CHART
chart = new AmCharts.AmPieChart();
chart.dataProvider = chartData;
chart.titleField = "country";
chart.valueField = "litres";



// LEGEND
legend = new AmCharts.AmLegend();
legend.align = "center";
legend.markerType = "circle";
chart.balloonText = "[[title]]<br><span style='font-size:14px'><b>[[value]]</b> ([[percents]]%)</span>";
chart.addLegend(legend);

// WRITE
chart.write("chartdiv");
});
// changes label position (labelRadius)
function setLabelPosition() {

if (document.getElementById("rb1").checked) {


chart.labelRadius = 30;


chart.labelText = "[[title]]: [[value]]";


} else {


chart.labelRadius = -30;

chart.labelText = "[[percents]]%";
}
chart.validateNow();
}


// makes chart 2D/3D


function set3D() {
if (document.getElementById("rb3").checked) {
chart.depth3D = 10;
chart.angle = 10;
} else {
chart.depth3D = 0;
chart.angle = 0;
}
chart.validateNow();
}

// changes switch of the legend (x or v)
function setSwitch() {
if (document.getElementById("rb5").checked) {
legend.switchType = "x";
} else {
legend.switchType = "v";
}
legend.validateNow();

}



</script>

最佳答案

您无法从 JavaScript 直接访问 mysql 数据库。您必须向服务器询问一些数据。通常,您需要获取 JSON 格式的数据(使用 ajax):

Javascript(使用.getJSON()):

$.getJSON('/get-my-data.php', function(json) {
var chart;
var legend;

var chartData = json;

AmCharts.ready(function () {
chart = new AmCharts.AmPieChart();
chart.dataProvider = chartData;

// code ...
});
});

get-my-data.php(使用mysqli):

$mysqli = new mysqli("localhost", "my_user", "my_password", "my_database");

$stats = array();

$query = "
SELECT `country`, `litres`
FROM `mytable`
";
$statement = $mysqli->prepare($query);

$result = $statement->get_result();
while ($data = $result->fetch_assoc())
{
$stats[] = $data;
}

echo json_encode($stats);

关于javascript - 在图表中显示 mysql 数据库中的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31132034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com