我需要在我的網站上顯示一個圖表(來自SQL數據)。所以我決定使用chart.js。我在互聯網上找到了一個例子。但我有一個問題:如何將包含在HTML頁面中的變量傳遞給PHP,然後用JS顯示它 - 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) {
}
});
});
NOP,這不是真的,我想獲得一個變量形式的這部分(HTML):
那麼,只需在你想要的地方添加回聲?編輯我的回答 –
我真的很抱歉,但我不明白你說什麼。我有一個變量,就像我說的HTML中的$變量,我想在PHP中讀取它,所以我不明白爲什麼我們做一個'POST' – user46510