Reputation: 17
I have this issue passing the data from an array variable to the python javascript function. Below is the entire script
array1 =[['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]];
self.response.out.write('<script type="text/javascript">'+
'google.load("visualization", "1", {packages:["corechart"]});'+
'google.setOnLoadCallback(drawChart);'+
'function drawChart() { '+
'var data = google.visualization.arrayToDataTable({0});' +
'var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);} '+
'</script> '.json.dumps(array1))
This is the javascript code which i want to convert to the python format wherein the array required for arrayToDataTable() will be fetched through queries. Currently static version of it (array1 above) doesn't work
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]]);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
chart.draw(data);
}
</script>
Please let me know how to pass the data (array) from the python to the javascript so that the chart gets loaded.
Upvotes: 1
Views: 227
Reputation: 301
This will work.
array1 =[['X-val', 'Y-val'], [4, 5], [8, 12], [11, 14]];
self.response.out.write("""<script type="text/javascript">
google.load("visualization", "1", {{packages:["corechart"]}});
google.setOnLoadCallback(drawChart);
function drawChart() {{
var data = google.visualization.arrayToDataTable({0});
var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);}}
</script> """.format(json.dumps(array1)))
Upvotes: 2
Reputation: 39626
Your current solution doesn't work because format
(you missed it, right?) calls before strings concatenated.
In current case I would prefer concatenation over format to prevent braces escaping:
js_code = '''
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable(''' + json.dumps(array1) + ''');
var chart = new google.visualization.LineChart(document.getElementById("casestrend"));chart.draw(data);}
</script>
'''
Upvotes: 2