You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Flask将数据库数据传递给外部Chart.js文件?

解决Flask向外部Chart.js文件传递数据的问题

核心原因很简单:Flask的Jinja2模板引擎只会渲染.html这类模板文件,外部的.js文件是浏览器直接请求的静态资源,不会经过Flask的模板渲染,所以你直接在chartjs.js里用{% values %}肯定无效。下面给你三种可行的解决办法:

方法一:通过全局变量传递数据

在HTML里用<script>把Flask传递的数据转成全局变量,外部JS直接读取这个变量即可:

修改后的index.html:

<canvas id="myChart"></canvas>
<script>
  // 把Flask传来的fruits转成JSON格式,挂载到全局window对象上
  window.fruitsData = {{ fruits | tojson }};
</script>
<script src="static/js/chartjs.js"></script>

修改后的chartjs.js:

const ctx2 = document.getElementById('myChart');
const background_color2 = ['#33a3ec', '#ff6384'];

// 从全局变量提取标签和数值(假设fruits是[{name: 'Orange', value:82}, ...]格式)
const labels = window.fruitsData.map(item => item.name);
const values = window.fruitsData.map(item => item.value);

new Chart(ctx2, {
    type: 'doughnut',
    data: {
        labels: labels,
        datasets: [{
            data: values,
            backgroundColor: background_color2,
            borderWidth: 10,
            borderColor: "#fbfbfb"
        }]
    },
    options: {
        scales: {
            display: false
        },
        animation: {
            duration: 1000,
            animateRotate: true,
            render: false
        },
        plugins: {
            title: {
                display: true,
                text: "Juice fruits"
            },
            legend: {
                display: true,
                position: 'bottom'
            }
        }
    }
});

方法二:通过HTML元素的data属性传递数据

把数据存在canvas元素的自定义data属性里,JS读取后解析使用:

修改后的index.html:

<!-- 把fruits转成JSON存在data-fruits属性中 -->
<canvas id="myChart" data-fruits="{{ fruits | tojson }}"></canvas>
<script src="static/js/chartjs.js"></script>

修改后的chartjs.js:

const ctx2 = document.getElementById('myChart');
// 读取canvas的data属性并解析成JSON对象
const fruitsData = JSON.parse(ctx2.dataset.fruits);
const background_color2 = ['#33a3ec', '#ff6384'];

const labels = fruitsData.map(item => item.name);
const values = fruitsData.map(item => item.value);

new Chart(ctx2, {
    type: 'doughnut',
    data: {
        labels: labels,
        datasets: [{
            data: values,
            backgroundColor: background_color2,
            borderWidth: 10,
            borderColor: "#fbfbfb"
        }]
    },
    options: {
        scales: {
            display: false
        },
        animation: {
            duration: 1000,
            animateRotate: true,
            render: false
        },
        plugins: {
            title: {
                display: true,
                text: "Juice fruits"
            },
            legend: {
                display: true,
                position: 'bottom'
            }
        }
    }
});

方法三:通过AJAX请求动态获取数据

如果数据需要动态更新或者量比较大,可以单独写一个Flask接口返回数据,JS通过fetch请求获取:

修改api.py,添加数据接口:

from flask import jsonify
import sqlite3

@app.route('/')
def index():
    return render_template("index.html") 

@app.route('/api/fruits-data')
def fruits_data():
    fruits = []
    # 执行SQLite查询逻辑
    conn = sqlite3.connect('your_database.db')
    cursor = conn.cursor()
    cursor.execute('SELECT name, value FROM fruits_table')
    # 把查询结果转成JS能识别的格式
    fruits = [{'name': row[0], 'value': row[1]} for row in cursor.fetchall()]
    conn.close()
    return jsonify(fruits)

修改后的chartjs.js:

const ctx2 = document.getElementById('myChart');
const background_color2 = ['#33a3ec', '#ff6384'];

// 请求Flask接口获取数据,成功后初始化图表
fetch('/api/fruits-data')
  .then(response => response.json())
  .then(fruitsData => {
    const labels = fruitsData.map(item => item.name);
    const values = fruitsData.map(item => item.value);

    new Chart(ctx2, {
        type: 'doughnut',
        data: {
            labels: labels,
            datasets: [{
                data: values,
                backgroundColor: background_color2,
                borderWidth: 10,
                borderColor: "#fbfbfb"
            }]
        },
        options: {
            scales: {
                display: false
            },
            animation: {
                duration: 1000,
                animateRotate: true,
                render: false
            },
            plugins: {
                title: {
                    display: true,
                    text: "Juice fruits"
                },
                legend: {
                    display: true,
                    position: 'bottom'
                }
            }
        }
    });
  })
  .catch(error => console.error('获取数据失败:', error));

内容的提问来源于stack exchange,提问作者F A Fernández

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 04:18:23