所以,我将我的数据从phpMyAdmin MySQL提取到chart.js,但我需要使用AJAX,但AJAX如何与Chart.js一起使用?

问题描述 投票:0回答:3

如何将AJAX放在Chart.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())上调用它,但如果我使用document.getElementById("myChart"),我将把<canvas id="myChart" width="100" height="40"></canvas>放在哪里

在此先感谢大家!

javascript php ajax chart.js
3个回答
0
投票

你可以做点什么

$.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

0
投票

您需要做的是使生成此数据的代码可通过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 The Right Way


0
投票

我终于使用了AJAX,但问题是,每当我在phpMyAdmin中更改一些数据时都不是实时的,我需要在网站上刷新它。 这是我的代码:ajax.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);
    }
});

});

这是我在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);

?>

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

© www.soinside.com 2019 - 2024. All rights reserved.