Flask框架:运用Ajax轮询动态绘图

Ajax是异步JavaScript和XML可用于前后端交互,在之前《Flask 框架:运用Ajax实现数据交互》简单实现了前后端交互 , 本章将通过Ajax轮询获取后端的数据,前台使用echart绘图库进行图形的生成与展示 , 后台通过render_template方法返回一串JSON数据集 , 前台收到后将其应用到绘图库上 , 实现动态监控内存利用率的这个功能 。
首先LyShark先来演示一下前端如何运用AJAX实现交互 , 通过$.ajax定义ajax开始标志,并指定url,type,datetype等信息,通过setInterval设置一个1000毫秒的定时器,每隔一段时间则去后端取数据 。
<!-- # 署名权 # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com--><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script><script type="text/javascript" src="https://cdn.lyshark.com/javascript/echarts/5.3.0/echarts.min.js"></script></head><body><!--设定一个定时器,每隔1000毫秒向后端发送请求--><script type="text/javascript">$(function () {fetchData();setInterval(fetchData, 1000);});function fetchData(){$.ajax({url:"/",type:"POST",dataType: 'json',success:function (recv) {console.log("[lyshark.com] 获取到时间:" + recv.response[0]);console.log("[lyshark.com] 获取到数据:" + recv.response[1]);}})}</script></body>后端只需要根据前端需要的格式返回系统中的CPU利用率(此处模拟) , 并使用json.dumps({"response":[times,data]})推送到前端即可 。
# 署名权# right to sign one's name on a piece of work# PowerBy: LyShark# Email: me@lyshark.comfrom flask import Flask,render_template,requestimport json,time,randomasync_mode = Noneapp = Flask(import_name=__name__,static_url_path='/python',# 配置静态文件的访问url前缀static_folder='static',# 配置静态文件的文件夹template_folder='templates') # 配置模板文件的文件夹@app.route('/',methods=['POST','GET'])def index():if request.method == "GET":return render_template("index.html")elif request.method == "POST":times = time.strftime("%M:%S", time.localtime())data = https://www.huyubaike.com/biancheng/[random.randint(1,100)]return json.dumps({"response":[times,data]})if __name__ == '__main__':app.run()运行这段代码 , 然后打开控制台,则可以看到如下数据,前台会每隔一秒向后端请求数据;

Flask框架:运用Ajax轮询动态绘图

文章插图
如果上方绘制可以被正确执行,那么想要实现轮询绘图只需要封装实现一个update()自定义绘图函数,该函数内将得到的数据统一放入到数组内 , 并调用封装好的display()函数,将数据绘制到前台 。
<!-- # 署名权 # right to sign one's name on a piece of work # PowerBy: LyShark # Email: me@lyshark.com--><!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><script type="text/javascript" src="https://cdn.lyshark.com/javascript/jquery/3.5.1/jquery.min.js"></script><script type="text/javascript" src="https://cdn.lyshark.com/javascript/echarts/5.3.0/echarts.min.js"></script></head><body><!--定义绘图区域--><div id="main" style="height:300px;width:80%;border:1px solid #eecc11;padding:10px;"></div><!--调用百度的绘图库,进行图片的绘制工作.--><script type="text/javascript" charset="UTF-8">var display = function(time,cpu) {var main = echarts.init(document.getElementById(("main")));var option = {xAxis: {boundaryGap:false,boundaryGap:false,type: 'category',data: time},yAxis: {type: 'value'},series: [{type: 'line',areaStyle:{},data: cpu}]};main.setOption(option,true);};</script><!--update()函数具体执行的任务,其主要只保留前十条数据.--><script type="text/javascript" charset="UTF-8">// 负责对参数的解析var time =["","","","","","","","","",""];var cpu = [0,0,0,0,0,0,0,0,0,0];var update = function(recv){time.push(recv.response[0]);cpu.push(parseFloat(recv.response[1]));if(time.length >=10){time.shift();cpu.shift();console.log("处理后的时间数据:" + time);console.log("处理后的CPU数据:" + cpu);display(time,cpu)// 调用绘图函数}};</script><!--设定一个定时器,每隔1000毫秒向后端发送请求--><script type="text/javascript">$(function () {fetchData();setInterval(fetchData, 1000);});function fetchData(){$.ajax({url:"/",type:"POST",dataType: 'json',success:function (recv) {console.log("获取到时间:" + recv.response[0]);console.log("获取到数据:" + recv.response[1]);// 传递给处理函数update(recv)}})}</script></body>

推荐阅读