教程 chartjs tutorial

使用 Axios

Chart.js 的数据可以通过多种方式异步获取。Axios 是一个基于 Promise 的 HTTP 客户端,使用简洁,支持拦截器和请求取消等功能,适合复杂场景。

下面示例展示如何用 Axios 请求数据,并更新折线图的数据内容。

js
const ctx = document.getElementById("axiosChart").getContext("2d");

const axiosChart = new Chart(ctx, {
  type: "bar",
  data: {
    labels: [],
    datasets: [
      {
        label: "访问量",
        data: [],
        backgroundColor: "rgba(255, 159, 64, 0.7)",
      },
    ],
  },
  options: {
    responsive: true,
    plugins: {
      legend: { display: true },
    },
  },
});

// 使用 Axios 获取数据
axios
  .get("https://jsonplaceholder.typicode.com/comments?_limit=5")
  .then((response) => {
    const data = response.data;
    axiosChart.data.labels = data.map((item) => "评论ID " + item.id);
    axiosChart.data.datasets[0].data = data.map((item) => item.body.length);
    axiosChart.update();
  })
  .catch((error) => {
    console.error("Axios 请求失败", error);
  });
在线代码演示
源码
<!DOCTYPE html>
<html lang="zh">

<head> <meta charset="UTF-8" /> <title>使用 Axios 示例</title> <script src="https://cdn.jsdelivr.net/npm/chart.js&quot;&gt;&lt;/script&gt; <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js&quot;&gt;&lt;/script&gt; <style> body { max-width: 700px; margin: 2rem auto; font-family: sans-serif; background: #f9f9f9; padding: 1rem; text-align: center; }

canvas {
  background: #fff;
  border: 1px solid #ccc;
  margin: 1rem auto;
}

</style> </head>

<body> <canvas id="axiosChart" width="700" height="400"></canvas> <script> (function () { const ctx = document.getElementById(‘axiosChart’).getContext(‘2d’);

  const axiosChart = new Chart(ctx, {
    type: 'bar',
    data: {
      labels: [],
      datasets: [{
        label: '访问量',
        data: [],
        backgroundColor: 'rgba(255, 159, 64, 0.7)'
      }]
    },
    options: {
      responsive: true,
      plugins: {
        legend: { display: true }
      }
    }
  });

  // 使用 Axios 获取数据
  axios.get('https://jsonplaceholder.typicode.com/comments?_limit=5')
    .then(response =&gt; {
      const data = response.data;
      axiosChart.data.labels = data.map(item =&gt; '评论ID ' + item.id);
      axiosChart.data.datasets[0].data = data.map(item =&gt; item.body.length);
      axiosChart.update();
    })
    .catch(error =&gt; {
      console.error('Axios 请求失败', error);
    });
})();

</script> </body>

</html>