我是 Django 新手。我正在制作民意调查应用程序,并想使用 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
});
});
问题是仅显示最后一个民意调查问题的图表。谢谢
最佳答案
这是因为在每个 for 循环中,question_id
都会被覆盖。您可能想做这样的事情:
$('.chart').each(function() {
var that = this;
var question_id = $(this).attr('id');
$.getJSON('/er/poll/'+question_id ,function(data) {
$(that).highcharts({
...
这样,在渲染页面后,您可以循环遍历每个 div
并渲染相应的图表。
更好:使用 data-id="{{ book.id }}"
并使用 $(this).data('id')
检索它避免将 id 属性用于并非真正用途的内容。
关于javascript - Django 中使用 ajax 的 Highcharts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39144583/