我正在尝试将一个变量从我的django视图传递到javascript作为二维数组,这样我就可以填充一个谷歌图表DataTable。
有人可以解释为什么这有效:
var data=new google.visualization.arrayToDataTable([[1,2,3],
[4,5,6]])
但这不是:
foo = [[1,2,3], [4,5,6]]
foo = json.dumps(foo) # the foo stuff is in the django view. i'm just trying to be clear as to what foo is.
var data=new google.visualization.arrayToDataTable({{ foo|safe }})# i've tried this with quotes and without safe. both as json and not.
我试过了:
foo = [json.dumps(i) for i in foo]
我根本没有尝试过json。我试过传递numpy数组,元组。我尝试使用data.addRows
填充DateTable,我尝试迭代并使用data.addRow
。和其他100件事一样......
我显然遗漏了一些重要的东西,因为我没有做任何事情。
为什么当我为DataTable硬编码数据时它是否有效但是当我尝试从我的django视图传递相同的数据时它会失败?
任何帮助都将受到赞赏,因为我的蓝色谷歌链接...
答案 0 :(得分:1)
根据我的经验,下面的示例应该可以使用
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var djangodata = {{djangodict|safe}};
var data = google.visualization.arrayToDataTable();
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
在你看来,我想你可以写出类似的东西;以下
dictdata=[
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]
return render_to_response{template,
'djangodict': json.dumps(dictdata),
.... other variables here
}
如果您正在为此图表创建模板,这应该可以正常工作。但是,如上所示在脚本中声明django变量非常重要。
var djangodata = {{djangodict|safe}};
如果你不这样做,事情可能根本不起作用: - (
我所做的与上述解决方案有所不同。我实际创建了一个模板标签,将数据变量传递给上面的javascript,让它按照我的意愿绘制图表。 仅仅因为我想在仪表板页面上包含我的图表,这样就可以了!