前言

目录

前言

1.引入库

2.flask链接MYSQL读取数据

3.HTML页面echarts绘图

4.结果实现

总结:


 

ECharts 是一个使用 JavaScript 实现的开源可视化库,涵盖各行业图表,满足各种需求。

ECharts 遵循 Apache-2.0 开源协议,免费商用。

ECharts 兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Safari等)及兼容多种设备,可随时随地任性展示。

AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML)。

AJAX 不是新的编程语言,而是一种使用现有标准的新方法。

AJAX 最大的优点是在不重新加载整个页面的情况下,可以与服务器交换数据并更新部分网页内容。

AJAX 不需要任何浏览器插件,但需要用户允许JavaScript在浏览器上执行

Flask通常被称为 微框架。 它旨在保持应用程序的核心简单且可扩展。 Flask没有用于数据库处理的内置抽象层,也没有形成验证支持。 相反,Flask支持扩展以将这些功能添加到应用程序中。部分流行的Flask扩展将在本教程后续章节中讨论。

1.引入库

from flask import Flask,render_template,url_for
from flask_cors import CORS
from pip import main
import pymysql
import json

2.flask链接MYSQL读取数据

app=Flask(__name__)
CORS(app,supports_credentials=True)
@app.route("/")
def hello():
    return render_template('data.html')
@app.route("/test",methods=('GET','POST'))
def test():
    conn=pymysql.connect(host='127.0.0.1',user='root',password='123456',db='sys')
    cur=conn.cursor()
    sql='SELECT t.id,t.scarly ,t.score from test1 t'
    cur.execute(sql)
    u=cur.fetchall()
    print(u)
    jsonData={}
    x=[]
    y=[]
    z=[]
    for data in u :
        x.append(data[0])
        y.append(data[1])
        z.append(data[2])
 
    jsonData['x']=x
    jsonData['y']=y
    jsonData['z']=z
    #json.dumps()用于将dict类型的数据转换成str,因为如果直接将dict类型的数据写入json会报错,因此将数据写入时需要用到此函数
    j=json.dumps(jsonData)
 
    cur.close()
    conn.close()
    return(j)
if __name__ == '__main__':
    app.run(debug=True)

3.HTML页面echarts绘图

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>炫酷的ECharts</title>
    
 
</head>
 <!-- 为ECharts准备一个具备大小(宽高)的Dom -->
<div id="main" style="width: 800px;height:500px;margin: 0 auto;"></div>

<!--引入jquery.js-->
<script src="../static/js/jquery.js"></script>
<!--引入echarts.js-->
<script src="../static/js/echarts.js"></script>

<script type="text/javascript">
 
    var myChart = echarts.init(document.getElementById('main'));
 
    var app = {
        x:[],
        y:[],
        z:[]
    };
 
    // 发送ajax请求,从后台获取json数据
    $(document).ready(function () {
       getData();
       console.log(app.x);
       console.log(app.y)
       console.log(app.z)

    });
 
    function getData() {
         $.ajax({
            url:'http://localhost:5000/test',
            data:{},
            type:'GET',
            async:false,
            dataType:'json',
            success:function(data) {
                app.x = data.x;
                app.y = data.y;
                app.z = data.z;
                myChart.setOption({
                title: {
                        text: '不同商品价格及评分趋势'
                    },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                    type: 'cross',
                    crossStyle: {
                        color: '#999'
                    }
                    }},
                toolbox: {
                                feature: {
                                dataView: { show: true, readOnly: false },
                                magicType: { show: true, type: ['line', 'bar'] },
                                restore: { show: true },
                                saveAsImage: { show: true }
                                }
                            },
                legend: {
                        data:['练习测试']
                    },
                 xAxis: {
                        data: app.x ,
                        axisPointer: {
                                type: 'shadow'
                                }
                    },
                yAxis: [{
                            type: 'value',
                            name: '价格',
                            min: 0,
                            max: 70,
                            interval: 5,
                            // data:app.y
                            },
                            {
                            type: 'value',
                            name: '评分',
                            min: 0,
                            max: 10,
                            interval: 1,
                            axisLabel: {
                                formatter: '{value} 分'
                            }
                            }
                        ],
                series: [
                    {
                    name: '价格',
                    type: 'bar',
                    tooltip: {
                        valueFormatter: function (value) {
                        return value + ' 元';
                        }
                    },
                    data: app.y
                    },
                    {
                    name: '评分',
                    type: 'line',
                    yAxisIndex: 1,
                    tooltip: {
                        valueFormatter: function (value) {
                        return value + ' 分';
                        }
                    },
                    data:  app.z
                    }
                ]
                
                })
            },
            error:function (msg) {
                console.log(msg);
                alert('系统发生错误');
            }
        })
    };
 
</script>


<body>
 
</body>
</html>

4.结果实现

总结


echarts1.国人开发,文档全,便于开发和阅读文档。 2.图表丰富,可以适用各种各样的功能 

通过ajax实现前端与后端数据的请求与传输。

更多推荐

通过ajax异步交互实现echarts绘图