gpt4 book ai didi

javascript - 如何将 HTML 页面中包含的变量传递给 PHP,然后用 JS 显示 - Chart.js

转载 作者:行者123 更新时间:2023-12-03 03:33:59 26 4
gpt4 key购买 nike

我需要在我的网站上显示图表(来自 SQL 数据)。所以我决定使用chart.js。我在互联网上找到了一个例子。但我有一个问题:

我想知道如何将HTML页面中包含的变量传递给PHP(发出请求sql),然后用JS显示它。我找不到这个信息。你能帮我一下吗?

这是示例代码:

HTML:

<html>
<head>
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/Chart.min.js"></script>
<script type="text/javascript" src="assets/js/linegraph.js"></script>
</head>

<body>
<header>
</header>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>
</body>
</html>

PHP:

<?php
//setting header to json
header('Content-Type: application/json');

//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '*****');
define('DB_NAME', 'Michel');

//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = 'SELECT heure, payload FROM reception ORDER BY date DESC LIMIT 10';

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
$data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);
?>

JS:

$(document).ready(function(){
$.ajax({
url : "graphdata.php",
type : "GET",
success : function(data){
console.log(data);

var heure = [];
var payload = [];

for(var i in data) {
heure.push("Heure " + data[i].heure);
payload.push(data[i].payload);
}

var chartdata = {
labels: heure,
datasets: [
{
label: "payload",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(59, 89, 152, 0.75)",
borderColor: "rgba(59, 89, 152, 1)",
pointHoverBackgroundColor: "rgba(59, 89, 152, 1)",
pointHoverBorderColor: "rgba(59, 89, 152, 1)",
data: payload
}
]
};

var ctx = $("#mycanvas");

var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error : function(data) {

}
});
});

最佳答案

你在谈论这样的事情吗?

在 JS 方面:

$.ajax({
url: 'test.php',
method: 'POST',
data: {
filter: '<?php echo $Variable; ?>',
},
success: function(r) {
console.log(r);
}
});

然后,在 PHP 端您可以使用

<?php
echo $_POST['filter']; //outputs someValue

这就是你的想法吗?

关于javascript - 如何将 HTML 页面中包含的变量传递给 PHP,然后用 JS 显示 - Chart.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45955330/

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