- echarts參考官方教程
5 分鍾上手 ECharts
效果 - 后台拼湊數據
后台代碼,使用TemplateView類。傳遞數據到前台 echarts.html
class Echarts_html(TemplateView): template_name = "templeate/app01/echarts.html" def get_context_data(self, **kwargs): context = super(Echarts_html, self).get_context_data(**kwargs) aaa= { 'title': { 'text': 'ECharts 入門示例' }, 'tooltip': {}, 'legend': { 'data': ['銷量'] }, 'xAxis': { 'data': [] }, 'yAxis': {}, 'series': [{ 'name': '銷量', 'type': 'bar', 'data': [] }] } articles = Article.objects.all() for item in articles: aaa['xAxis']['data'].append(item.title) aaa['series'][0]['data'].append(item.read_count) context['aaa'] = aaa return context
<body> <!-- 為ECharts准備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基於准備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數據 var option = {{ aaa | safe}}; myChart.setOption(option); </script>
</body> - 前台js處理數據
后台代碼,很簡單直接返回數據
class Echarts_html(TemplateView): template_name = "templeate/app01/echarts.html" def get_context_data(self, **kwargs): context = super(Echarts_html, self).get_context_data(**kwargs) context['articles'] = Article.objects.all() return context
前台代碼,js處理,注意的一點就是js中數組push(類似append)必須是字符串或者數字,直接"xxxx"轉成字符串。
<body> <!-- 為ECharts准備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基於准備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數據 var option = { 'title': { 'text': 'ECharts 入門示例' }, 'tooltip': {}, 'legend': { 'data': ['閱讀量'] }, 'xAxis': { 'data': [] }, 'yAxis': {}, 'series': [{ 'name': '閱讀量', 'type': 'bar', 'data': [] }] } {% for item in articles %} option['xAxis']['data'].push("{{ item.title }}") option['series'][0]['data'].push("{{ item.read_count }}") {% endfor %} console.log(option) // 使用剛指定的配置項和數據顯示圖表。 myChart.setOption(option); </script> </body>