我已经在这里查看了一些类似的问题:How can I pass data from Flask to JavaScript in a template?
我正在尝试使用this example创建谷歌图表,其中我的数据来自数据库查询,然后对其进行解析和格式化以通过 Google 的数据源 python 库传递,然后转换为 json 字符串。从那里它应该通过我的 HTML 文件中的 JavaScript 函数传递,以便填充 Google Charts 表。最后一部分似乎给我带来了麻烦。这是我在 flask 中的函数的主要内容:
description = {"count": ("number", "Count"),"type": ("string", "Type")}
data=[]
rows = cur.fetchall()
# formats MySQL data for JSON string
for row in rows:
js = {'type': row[0], 'count': row[1]}
data.append(js)
# Loading it into gviz_api.DataTable (from Google Charts template)
data_table = gviz_api.DataTable(description)
data_table.LoadData(data)
# Create a JSON string. (from google charts template)
json= data_table.ToJSon(columns_order=("type", "count"), order_by="count")
render_template('myhtml.html' , json=json)
在 Flask 中函数的末尾,然后通过我的 html 文件中的以下 JavaScript 函数传递:
<script>
...
// taken from the Google Charts example
google.load('visualization', '1', {packages:['table']});
google.setOnLoadCallback(drawTable);
var json = '{{ json }}'
function drawTable(json) {
var json_table = new google.visualization.Table(document.getElementById('table_div_json'));
var json_data = new google.visualization.DataTable((json), 0.6);
json_table.draw(json_data, {showRowNumber: true});
}
图表没有绘制,我只剩下图表的标题。我不认为这是我的数据或 HTML 部分(我已省略)的格式的问题,因为它是直接从 Google Charts 模板中获取的,所以我一直在尝试在我的JavaScript(我对它还很陌生)。这个字符串不能以这种方式传递给 JavaScript 函数吗?有哪些替代方法可以完成?任何指示和建议都会很棒。
最佳答案
可能必须逃避它,例如:
{{json | safe}}
关于javascript - 将 MySQL 数据从 Flask 传递到 JavaScript 以用于 Google Charts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33444115/