我最近尝试用 flask 制作仪表板,其中包含来自 mongodb 的数据。但我无法将数据发送到 chart.js。我从 mongodb 获取数据并发送到 javascript 并尝试使用 jinja2 循环数据。
@app.route("/dashboard")
def dashboard():
limit = request.args.get("limit",12,type=int)
dashboardDatas = mongo.db.dashBoard
dashDatas = dashboardDatas.find().limit(limit)
return render_template("dashboard.html", dashDatas = dashDatas)
<canvas id="myChart" height="50"></canvas>
<script>
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [ {% for item in dashDatas %}
'{{item._id}}',
{% endfor %} ],
datasets: [{
label: '# of Votes',
data: [ {% for item in dashDatas %}
{{item.logistic}},
{% endfor %}],
borderColor: [
'rgba(255, 99, 132, 1)',
],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
],
borderWidth: 0.5
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
</script>
我得到了空图表。我做错了什么?
最佳答案
我的方法是将标签和数据存储在 Flask View 中的列表中,将它们传递给模板并使用 tojson
将它们转换为 JSON筛选。
假设您有 labels = ['a', 'b', 'c']
和 data = [1, 2, 3]
在你看来。您可以将它们传递给模板中的 Chart.js
let chart = new Chart(ctx, {
type: 'line',
data: {
labels: {{ labels|tojson }},
datasets: [{
label: 'My 1st dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: {{ data|tojson }}
}]
});
关于javascript - 如何使用 flask 将数据传递给 chart.js?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64874084/