思路:
统一返回数据类型为json,然后前端发起Ajax请求后台数据接口
views.py
def count_blog(request): # 下面等价于:select distinct auth,count() as blog_count from cms_blogpost group by auth # auth_count_blog=BlogPost.objects.values('auth').distinct().annotate(blog_count=Count('auth')).all() # print '第1个作者的数量为:', auth_count_blog # auth_count_blog=[{'blog_count': 1, 'auth': u'guchen'}, {'blog_count': 1, 'auth': u'u6c6au5a07'}, # {'blog_count': 7, 'auth': u'u8c37u6668'}] auth_count_blog={'blog_count': [10, 15, 20], 'auth': ["guchen", "wangjiao", "zhuzhu"]} # 向js中传递数据必须json.dumps()处理 return render(request, 'count_blog.html', {'auth_count_blog': json.dumps(auth_count_blog)})
count_blog.html
<!--echarts图表--> <script type="text/javascript"> // 基于准备好的dom,初始化echarts实例 var myChart = echarts.init(document.getElementById('main')); // 显示标题,图例和空的坐标轴 myChart.setOption({ title: { text: '异步数据加载示例' }, tooltip: {}, legend: { data:['销量'] }, xAxis: { data: [] }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: [] }] }); var auth_count_blog={}; //请求前先不要获取后端返回的数据,先定义空的字典 $.get('/count_blog/').done(function (auth_count_blog) { <!--$.ajax({--> //用这种请求没有出来图 auth_count_blog = {{auth_count_blog|safe}}; // 获取后台传来的数据需要加上safe过滤 <!--url: '/count_blog/',--> <!--type: 'POST',--> <!--data: {},--> <!--dataType: 'json',--> <!--success:function(auth_count_blog){--> myChart.setOption({ xAxis: { data: auth_count_blog['auth'] //获取字典的作者 }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: auth_count_blog.blog_count //获取对应的作者的博客数 }] }); <!--}--> }); </script> {% endblock %} </body> </html>