前言: 后面要开发测试管理平台,需要用到数据可视化,所以研究了一下
先看下最后的图吧,单击最上方的按钮可以控制柱状图显隐
views.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import json from django.shortcuts import render import pymysql def showcase(request): """ 从数据库中读取作者的用例信息,并用于前台可视化展示 :param request: :return: """ db = pymysql.connect("localhost", "root", "guchen", "guchen_test", charset='utf8') cursor = db.cursor() sql = "select * from userCaseInfo" cursor.execute(sql) results = cursor.fetchall() print results # 向js中传递数据必须json.dumps()处理 return render(request, "showcase.html", {'caseInfo': json.dumps(list(results))})
showcase.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>showcasetitle>
{# 引入jQuery#}
<script src="http://code.jquery.com/jquery-latest.js">script>
<script src="../static/js/echarts.js">script>
head>
<body>
<div id="main" style="width: 1000px;height: 500px">
{% block content %}
<script type="text/javascript">
// 基于准备好的dom,初始化echarts实例
var myChart = echarts.init(document.getElementById('main'));
// 显示标题,图例和空的坐标轴
myChart.setOption({
legend: {},
tooltip: {},
dataset: {
source: [
[],
[], //这里一定要把最内层的数据清除掉
[]
]
},
xAxis: {type: 'category'},
yAxis: {},
// Declare several bar series, each will be mapped
// to a column of dataset.source by default.
series: [
{type: 'bar'},
{type: 'bar'},
{type: 'bar'}
]
});
var caseInfo={}; //请求前先不要获取后端返回的数据,先定义空的字典(去掉也没事)
// 注意这里的参数值,showcase表示视图函数,caseInfo是后台传过来的数据
$.get('/showcase/').done(function (caseInfo) {
caseInfo = {{ caseInfo|safe}}; // 获取后台传来的数据需要加上safe过滤
uname = caseInfo[0][1]
// 将source中不变的第一个列表元素初始化进来
var source = [['product', '总数', '成功', '失败']];
// 使用for循环将caseInfo中的数据循环遍历push进source列表中
for(var i=0; i< caseInfo.length;i++)
{
source.push([caseInfo[i][1], caseInfo[i][2], caseInfo[i][3], caseInfo[i][4]])
myChart.setOption({
dataset: {
// 引用添加了数据的变量source
source: source
}
});
}
});
script>
{% endblock %}
div>
body>
html>
使用的Echarts模板是:
option = { legend: {}, tooltip: {}, dataset: { source: [ ['product', '总数', '成功', '失败'], ['Matcha Latte', 43.3, 85.8, 93.7], ['Milk Tea', 83.1, 73.4, 55.1], ['Cheese Cocoa', 86.4, 65.2, 82.5], ['Walnut Brownie', 72.4, 53.9, 39.1] ] }, xAxis: {type: 'category'}, yAxis: {}, // Declare several bar series, each will be mapped // to a column of dataset.source by default. series: [ {type: 'bar'}, {type: 'bar'}, {type: 'bar'} ] };