Echarts+jsonp+flask 数据可视化
2019-05-03 本文已影响0人
清风徐来_简
-
py文件
from flask import Flask, render_template, Response, request ,jsonify import json app = Flask(__name__) xtype = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] xdata = [5, 20, 36, 10, 10, 20] json_data = json.dumps({"xtype": xtype, "xdata": xdata}) @app.route('/echarts') def tem(): return render_template('bar.html') @app.route('/data') def data(): callback = request.args.get('callback') # 支持jsonp方式的api接口 return Response('{}({})'.format(callback, json_data)) # 【如果是这个格式的,那么 ↓ 就可以不使用jsonp方式。】 # return jsonify({"xtype": xtype, "xdata": xdata}) app.run()
-
bar.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>bar</title> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/4.2.1/echarts.min.js"></script> </head> <body> <div id="main" style="width: 900px;height:600px;"></div> <script type="text/javascript"> function optionFactory(res) { var myChart = echarts.init(document.getElementById('main')); var option = { title: { text: 'ECharts 入门示例' }, toolbox: { show: true, feature: { saveAsImage: { show: true } } }, legend: { data: ['销量'] }, xAxis: { data: res.xtype }, yAxis: {}, series: [{ name: '销量', type: 'bar', data: res.xdata }] }; myChart.setOption(option); } $.ajax({ type: 'get', url: 'http://127.0.0.1:5000/data', dataType: "jsonp", // 指定此次请求是jsonp形式 // 【如果不使用jsonp方式,上面 ↑ 就可以那样写】 success: function (res) { optionFactory(res); }, error: function (msg) { console.log(msg); } }); </script> </body> </html>
-
访问:http://127.0.0.1:5000/echarts