简体   繁体   English

将MySQL数据从烧瓶传递到JavaScript以获取Google图表

[英]Passing MySQL data from flask to JavaScript for Google Charts

I've already checked out some similar questions here: How can I pass data from Flask to JavaScript in a template? 我已经在这里检查了一些类似的问题: 如何在模板中将数据从Flask传递到JavaScript?

I'm trying to create a google chart using this example , where my data is coming from a database query, which is then parsed and formatted to be passed through Google's datasource python library, then converted into a json string. 我正在尝试使用此示例创建一个google图表,其中我的数据来自数据库查询,然后将其解析并格式化为通过Google的数据源python库传递,然后转换为json字符串。 From there it is supposed to be passed through a JavaScript function in my HTML file in order to populate the Google Charts table. 从那里应该通过我的HTML文件中的JavaScript函数传递它,以便填充Google Charts表。 This last part seems to be causing me trouble. 这最后一部分似乎给我带来了麻烦。 Here is the meat of my function in 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)

at the end of my function in flask, which is then passed through the following JavaScript function in my html file here: 在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});
}

The chart is not drawn and I am left with only the header for the chart. 该图表未绘制,只剩下图表的标题。 I don't believe this is an issue with the format of my data or the HTML portion (which I've left out), for it is taken straight from the Google Charts template, so I've been trying to find problems in my JavaScript (which I am fairly new to). 我不认为这与我的数据或HTML部分的格式有关(我已经遗漏了),因为它直接取自Google Charts模板,因此我一直在尝试寻找问题JavaScript(我还很陌生)。 Can this string not be passed to the JavaScript function in this fashion? 不能以这种方式将此字符串传递给JavaScript函数吗? What alternative ways can it be done? 有哪些替代方法可以完成? Any pointers and suggestions would be great. 任何指示和建议都很好。

可能必须逃脱它,例如:

{{json | safe}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM