How to dynamically load database data in Echarts?

In order to dynamically load database data into echarts, you need to use a server-side scripting language (such as PHP, Python, etc.) to connect and manipulate the database, and then pass the data to echarts for dynamic loading.

Here is an example code using PHP and MySQL database to dynamically load data into Echarts.

  1. Firstly, import the Echarts library file and a DOM container in your HTML file.
<!DOCTYPE html>
<html>
<head>
  <title>动态加载数据到ECharts</title>
  <script src="https://cdn.staticfile.org/echarts/4.9.0/echarts.min.js"></script>
</head>
<body>
  <div id="chart" style="width: 600px; height: 400px;"></div>
</body>
</html>
  1. Create a PHP file (e.g. data.php) to connect to the database and retrieve data.
<?php
// 连接数据库
$servername = "localhost";
$username = "root";
$password = "password";
$dbname = "database_name";

$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接是否成功
if ($conn->connect_error) {
  die("连接失败: " . $conn->connect_error);
}

// 查询数据
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// 将数据转换为JSON格式
$data = array();
if ($result->num_rows > 0) {
  while($row = $result->fetch_assoc()) {
    $data[] = $row;
  }
}

// 关闭连接
$conn->close();

// 将JSON数据返回给前端
header('Content-Type: application/json');
echo json_encode($data);
?>
  1. Add a JavaScript script to your HTML file to use Echarts to load data.
<!DOCTYPE html>
<html>
<head>
  <title>动态加载数据到ECharts</title>
  <script src="https://cdn.staticfile.org/echarts/4.9.0/echarts.min.js"></script>
</head>
<body>
  <div id="chart" style="width: 600px; height: 400px;"></div>

  <script>
    // 使用ajax请求数据
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4 && xhr.status === 200) {
        var data = JSON.parse(xhr.responseText);
        renderChart(data);
      }
    };
    xhr.open('GET', 'data.php', true);
    xhr.send();

    // 使用echarts渲染图表
    function renderChart(data) {
      var chart = echarts.init(document.getElementById('chart'));

      var option = {
        xAxis: {
          type: 'category',
          data: data.map(function(item) {
            return item.xAxis;
          })
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: data.map(function(item) {
            return item.yAxis;
          }),
          type: 'line'
        }]
      };

      chart.setOption(option);
    }
  </script>
</body>
</html>

The above example demonstrates connecting and querying a database using PHP and MySQL, then returning the query results to the frontend in JSON format. The frontend uses JavaScript to request the data via Ajax and render the charts using echarts. You will need to modify the database connection information and query statements in the code according to your actual situation.

广告
Closing in 10 seconds
bannerAds