我正在尝试从数据库中获取数据,以显示在 graph.js 图表中。 我知道 ajax 的回调是异步的,我尝试设置超时,等待响应并将返回值设置为全局变量,但没有任何效果。 如果有人能告诉我这是如何工作的,我将不胜感激!谢谢
<body>
<canvas id="myChart"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var response = null;
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "fetch-graph.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("fetch");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr.responseText);
response = xhr.responseText;
} else {
alert("something went wrong");
}
}
}
var timerId = setInterval(function() {
if(response !== null) {
var chart = new Chart(ctx, {
// The type of chart we want to create
type: 'line',
// The data for our dataset
data: {
labels: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
datasets: [{
label: "Example Graph 1",
borderColor: 'rgb(255, 0, 100)',
//data: [45,23,39,12,34,56,67,78,90,78,73,74]
data: response
}]
}
});
clearInterval(timerId);
}
}, 1000);
</script>
</body>
这是 php 文件,从数据库获取值:
<?php
$connect = mysqli_connect("localhost", "max", "password", "graph");
if(isset($_POST['fetch'])){
$sql = "SELECT * FROM graph_data";
$query = mysqli_query($connect, $sql);
$row = mysqli_fetch_assoc($query);
$months = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'deb'];
for ($i = 0; $i<12; $i++){
echo $row[$months[$i]];
}
}
最佳答案
您也可以在 ajax 响应中添加。 在js页面中
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.bundle.js"> </script>
$.ajax({
url: "/your URL",
type: "post",
dataType: "json",
data: send your data what you want to send ,
success: function (response) {
if (response) {
let data = response;
var ctx = document.getElementById("doughutChart");
ctx.height = 150;
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
datasets: [{
data: data,
backgroundColor: [
"rgba(253, 11, 21, 0.9)",
"rgba(0, 123, 255,0.7)"
],
hoverBackgroundColor: [
"rgba(253, 11, 21, 0.9)",
"rgba(0, 123, 255,0.7)"
]
}],
labels: [
"Pending",
"Completed"
]
},
options: {
responsive: true
}
});
}
}
});
在动态图中,您必须以数组形式发送值。所以在ajax响应中我得到了数组中的值并将该数据传递到图表中。
关于javascript - 在图表中使用 ajax 响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45478634/