所以,我正在将数据从phpMyAdmin MySQL获取到chart.js,但我需要它与AJAX,但是AJAX如何与Chart.js一起工作?



如何将AJAX放在图表上.js?这是我的代码

// Chart
var ctx = document.getElementById("AreaChart");
var myLineChart = new Chart(ctx, {
type: 'line',
update: ({
duration: 200,
easing: 'easeOutBounce'
}),
data: {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Harvested",
lineTension: 0.3,
backgroundColor: "rgba(2,117,216,0.2)",
borderColor: "rgba(2,117,216,1)",
pointRadius: 6,
pointBackgroundColor: "rgba(2,117,216,1)",
pointBorderColor: "rgba(255,255,255,0.8)",
pointHoverRadius: 8,
pointHoverBackgroundColor: "rgba(2,117,216,1)",
pointHitRadius: 20,
pointBorderWidth: 2,
data: [<?php while($energy = mysqli_fetch_assoc($energy_set)) { echo h($energy['energyPercent'] . ','); } ?>],
}],
},

所以在data: [<?php while($energy = mysqli_fetch_assoc($energy_set)) { echo h($energy['energyPercent'] . ','); } ?>]。这是我可以完美地从MySQL中获取数据,但问题是需要刷新才能获取新数据。如何把AJAX放在那里?

我观看并阅读了一些 AJAX 教程,但就我而言,这有点难,尤其是我是 AJAX 的新手。

这是我的函数 ajax(),我将在 HTML 上调用它( body onload=ajax()) 但是如果我使用<canvas id="myChart" width="100" height="40"></canvas>,我将把document.getElementById("myChart")放在哪里

提前感谢大家!

你可以做类似的事情

$.ajax({
url: "/your/url/to/ajax.php",
method: "POST",
data: { id: 1 },
success: function(response) {
var label_array = [];
var data_array= [];
for(var i in response) {
label_array.push(response[i].Date);
data_array.push(response[i].value);
}
<Chart.js code>
} // End Success
})  // End Ajax

您需要做的是使生成此数据的代码可通过 URL 访问 - 这有时称为创建端点。通常,许多捆绑在一起的这些被称为应用程序编程接口(API)。这是一种让应用程序根据您请求的 url 及其参数显示、更新、删除或创建数据的方法。

在这种情况下,您可能会创建一个类似于https://yourhost.tld/energy.php的终结点。当您请求energy.php时,它会运行并获取您从$energy_set获取的数据,并将其作为 HTTP 响应返回。这可能看起来像这样:

<?php
header('Content-Type: application/json');
$data = [];
while($energy = mysqli_fetch_assoc($energy_set)) {
$data[] = $energy['energyPercent'];
}
echo json_encode($data);
return;

这大约是你能得到的准系统——如果你有很多端点,你可能想考虑一个像Lumen这样的小框架来帮助你组织你的代码并使其更安全。

因此,完成此操作后,您可以开始从浏览器中获取该数据。这可以通过多种方式完成,但最简单的方式如下所示:

// Using the fetch API - you can use jQuery.ajax instead, for example
fetch('https://yourhost.tld/energy.php')
.then(function(response) {
// Remove the chart data
chart.data.datasets.forEach((dataset) => {
dataset.data.pop();
});
// Add your response data back into the chart
chart.data.datasets.forEach((dataset) => {
dataset.data.push(response);
});
});

这真的很幼稚 - 您可能希望将数据清空和添加分解为函数,如文档所示。当您知道需要重建图表时,只需在修改其数据后调用chart.update()即可。此处概述如下: http://www.chartjs.org/docs/latest/developers/updates.html

因此,您的最终代码可能类似于以下内容:

fetch('https://yourhost.tld/energy.php')
.then(function(response) {
removeData(chart);
addData(chart, 'Harvested', response);
chart.update();
});

您还可以养成在响应中返回所有图表数据的习惯,以便您可以使用通用图表处理程序:

<?php
header('Content-Type: application/json');
$data = [];
while($energy = mysqli_fetch_assoc($energy_set)) {
$data[] = $energy['energyPercent'];
}
echo json_encode([
'label' => 'Harvested',
'data'  => $data
]);
return;

然后在你的JavaScript中...

fetch('https://yourhost.tld/energy.php')
.then(function(response) {
removeData(chart);
addData(chart, response.label, response.data);
chart.update();
});

如果有任何不清楚的地方,请随时提出问题。一旦你掌握了窍门,这个约定就很简单,但在你完成之前似乎很难。

我还要补充一点,虽然这段代码可能接近工作,但它不是"最佳实践";它更旨在说明它如何用尽可能少的代码工作。在原型或爱好项目中使用这样的代码是完全可以的,但是在构建一堆使用mysqli_fetch_assoc的端点之前,我会研究SQL注入和数据清理之类的东西。如果你有兴趣,看看PHP正确的方式。

我终于让它与 AJAX 一起工作,但问题是,每当我在 phpMyAdmin 中更改一些数据时,它都不是实时的,我需要在网站上刷新它。

这是我的代码:阿贾克斯.js

$(document).ready(function() {
$.ajax({
url: "http://localhost/projectZeus/private/data.php",
method: "GET",
async: true,
success: function(data) {
console.log(data);
var energy = [];
for(var i in data) {
energy.push(data[i].energyPercent);
}   
var chartdata = {
labels: ["Jan", "Feb", "Mar", "Apr", "May"],
datasets: [{
label: "Harvested",
lineTension: 0.3,
backgroundColor: "rgba(2,117,216,0.2)",
borderColor: "rgba(2,117,216,1)",
pointRadius: 6,
pointBackgroundColor: "rgba(2,117,216,1)",
pointBorderColor: "rgba(255,255,255,0.8)",
pointHoverRadius: 8,
pointHoverBackgroundColor: "rgba(2,117,216,1)",
pointHitRadius: 20,
pointBorderWidth: 2,
data: energy
}]
};
var ctx = $("#AreaChart");
var barChart = new Chart(ctx, {
type: 'line',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});

});


这是我在数据中的代码.php

<?php
require_once('initialize.php');
header('Content-Type: application/json');
global $db;
$sql = "SELECT energyPercent FROM energy";
$result = mysqli_query($db, $sql);
$data = array();
foreach($result as $row) {
$data[] = $row;
}
mysqli_free_result($result);
echo json_encode($data);

?>

如何在不刷新页面的情况下实时获取它?请帮忙,谢谢!

最新更新