我是Django的新手。我正在投票應用程序,並希望使用highcharts來顯示圖形。我有一個顯示所有投票的模板。我想以圖表的形式顯示相應的投票結果。模板的一部分:在Django使用ajax的Highcharts
{% for question in poll_questions %}
<div class="col-sm-6">
<div class="panel panel-default">
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
{{question.question_text}}
{% for choice in question.poll_choices_set.all %}
<div>
<label><input type="radio" name="{{question.pk}}" value="{{ choice.pk }}">  {{choice.choice_text}}</label>
</div>
{% endfor %}
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-6">
<div id="{{ question.pk }}" class="chart" style="height: 400px; width: 400px"></div><br>
<script>
var question_id = '{{ question.pk }}'
</script>
<script src="{% static 'er_interface/polls.js' %}"></script>
</div>
{% endfor %}
的Javascript文件 - polls.js:
$.getJSON('/er/poll/'+question_id ,function(data) {
$('#'+question_id).highcharts({
chart: {
type: 'pie'
},
title: {
text: question_id
},
tooltip: {
pointFormat: ':<b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: false
},
showInLegend: true
},
series: {
dataLabels: {
enabled: true,
formatter: function() {
return Math.round(this.percentage*100)/100 + ' %';
},
distance: 0,
}
}
},
series: data
});
});
的問題是,圖形顯示只爲最後的投票問題。謝謝
因爲您正在每個循環更新'question_id'的值。這樣做 - 'var question_id ='{{question.pk}}''在一個循環中意味着JS解釋器將讀取最新值,即*,即最後一個問題的ID。 – xyres
但它正確地從js文件打印控制檯中的數據。它只是沒有渲染圖表。 –