2016-08-25 33 views
0

我是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 }}">&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 
    }); 
}); 

的問題是,圖形顯示只爲最後的投票問題。謝謝

+0

因爲您正在每個循環更新'question_id'的值。這樣做 - 'var question_id ='{{question.pk}}''在一個循環中意味着JS解釋器將讀取最新值,即*,即最後一個問題的ID。 – xyres

+0

但它正確地從js文件打印控制檯中的數據。它只是沒有渲染圖表。 –

回答

1

這是因爲在每個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 S的渲染頁面,你循環後和渲染相應的圖表。

甚至更​​好:使用data-id="{{ book.id }}"並使用$(this).data('id')檢索它是否避免使用id屬性來表示它並非真正意義。

+0

我不得不使用問題id將圖表附加到div元素。 '這'不起作用。它顯示'未捕獲的錯誤:Highcharts錯誤#13:www.highcharts.com/errors/13'。謝謝。 –

+0

對不起,有點太快了。你確實在回調中失去了'這個'。更新了答案,應該立即開始工作。 –