javascript - Django 中使用 ajax 的 Highcharts

标签 javascript ajax django highcharts django-templates

我是 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 }}">&nbsp {{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/

相关文章:

javascript - 使用bunyan记录器登录nodejs,将DEBUG、INFO、ERROR打印到同一文件

javascript - 在 VueJS 中使用路由时设置超时错误

javascript - 返回 ajax 结果页面上上次看到的位置

javascript - AJAX 调用期间删除的文件扩展名

python - 有没有办法使用 setattr 来获取错误,而如果不将 setattr 与 django 模型一起使用,我会得到这个错误?

python - django url 中的正则表达式错误

django - 如何限制用户对自己的模型进行投票

javascript - 如何在 JSDoc 中创建类别?

javascript - 导航栏中的错误?

javascript - AJAX json 返回未定义