小程序ajax异步更新,微信小程序 Echarts 异步数据更新

微信小程序 Echarts 异步数据更新的练习,被坑了很多次,特作记录。

作者:罗兵

地址:https://www.cnblogs.com/hhh5460/p/9989805.html

0、效果图

20181120164744486617.png

1、视图

2、设置

//index.json

{

"usingComponents": {

"ec-canvas": "../../components/ec-canvas/ec-canvas"

}

}

3、样式

/**index.wxss**/

ec-canvas {

width: 100%;

height: 100%;

}

/**app.wxss**/

.container {

position: absolute;

top: 0;

bottom: 0;

left: 0;

right: 0;

display: flex;

flex-direction: column;

align-items: center;

justify-content: space-between;

box-sizing: border-box;

}

4、逻辑

/**index.js**/

// 载入组件

import * as echarts from ‘../../components/ec-canvas/echarts‘;

// 载入工具

//const util = require(‘../../utils/util.js‘)

let chart = null;

let month = [‘月‘, ‘月‘, ‘月‘, ‘月‘, ‘月‘, ‘月‘]; //月份

let evaporation = [0, 0, 0, 0, 0, 0]; //蒸发量

let precipitation = [0, 0, 0, 0, 0, 0]; //降水量

function initChart(canvas, width, height) {

chart = echarts.init(canvas, null, {

width: width,

height: height

});

canvas.setChart(chart);

chart.showLoading(); // 首次显示加载动画

var option = {

legend: {

data: [‘蒸发量‘, ‘降水量‘]

},

xAxis: {

data: [‘月‘, ‘月‘, ‘月‘, ‘月‘, ‘月‘, ‘月‘]

},

yAxis: {},

series: [{

name: ‘蒸发量‘,

type: ‘bar‘,

data: evaporation

}, {

name: ‘降水量‘,

type: ‘line‘,

data: precipitation

}]

};

chart.setOption(option);

chart.hideLoading(); // 隐藏加载动画

return chart;

};

Page({

data: {

ec: {

onInit: initChart

},

lastid: 0 // 哨兵

},

onReady() {

this.data.timer = setInterval(this.getData, 2000);

},

getData() { //请求后台数据

var that = this;

wx.request({

url: ‘http://127.0.0.1:5000/api/weather‘,

herder: {

"content-type": "application/json"

},

method: "POST",

data:{

id: that.data.lastid + 1 // 哨兵,记录上次数据表中的最后id

},

success: function(res){

that.setData({lastid: that.data.lastid + 1});

// 切片是能统一的关键!!

month = month.slice(1).concat(res.data.month); // 数组,先切片、再拼接

evaporation = evaporation.slice(1).concat(res.data.evaporation.map(parseFloat)); //注意map方法

precipitation = precipitation.slice(1).concat(res.data.precipitation.map(parseFloat));

chart.setOption({

xAxis: {

data: month

},

series: [{

name: ‘蒸发量‘, // 根据名字对应到相应的系列

data: evaporation

}, {

name: ‘降水量‘,

data: precipitation

}]

});

if(that.data.lastid == 12){clearInterval(that.data.timer);}

},

fail: function (res) {},

complete: function (res) {},

});

}

});

5、后端

# flask_restful_api.py

import sqlite3

from flask import Flask, request, render_template, jsonify

app = Flask(__name__)

def get_db():

db = sqlite3.connect(‘mydb.db‘)

db.row_factory = sqlite3.Row

return db

def query_db(query, args=(), one=False):

db = get_db()

cur = db.execute(query, args)

db.commit()

rv = cur.fetchall()

db.close()

return (rv[0] if rv else None) if one else rv

@app.before_request

def create_db():

# 建立连接

conn = sqlite3.connect(‘mydb.db‘)

c = conn.cursor()

# 创建表格

c.execute(‘‘‘DROP TABLE IF EXISTS weather‘‘‘)

c.execute(‘‘‘CREATE TABLE weather (id integer, month text, evaporation text, precipitation text)‘‘‘)

# 准备数据(格式:月份,蒸发量,降水量)

purchases = [(1,‘1月‘, 2, 2.6),

(2, ‘2月‘, 4.9, 5.9),

(3,‘3月‘, 7, 9),

(4,‘4月‘, 23.2, 26.4),

(5,‘5月‘, 25.6, 28.7),

(6,‘6月‘, 76.7, 70.7),

(7,‘7月‘, 135.6, 175.6),

(8,‘8月‘, 162.2, 182.2),

(9,‘9月‘, 32.6, 48.7),

(10,‘10月‘, 20, 18.8),

(11,‘11月‘, 6.4, 6),

(12,‘12月‘, 3.3, 2.3)

]

# 插入数据

c.executemany(‘INSERT INTO weather VALUES (?,?,?,?)‘, purchases)

conn.commit()

conn.close()

@app.route("/api/weather", methods=["GET","POST"])

def weather():

if request.method == ‘POST‘:

res = query_db("SELECT * FROM weather WHERE id = (?)", args=(request.json[‘id‘],)) #以后每次返回1个数据

return jsonify(month = [x[1] for x in res],

evaporation = [x[2] for x in res],

precipitation = [x[3] for x in res]) # 返回json格式

if __name__ == "__main__":

app.run(debug=True)

6、要点

a. 前端发送:herder: { "content-type": "application/json"};

前端接收:response.data(注意,微信将后台数据封装在res.data中, res.data是json格式)

b. 后端接收:request.json[‘id‘] ;

后端发送:jsonify

c. 本地测试设置:

20181120164744532515.png

7、参考

微信小程序Cannot read property ‘setData‘ of null错误:https://blog.csdn.net/qq_42183184/article/details/82356208

微信小程序wx.request组件的那些坑:https://www.cnblogs.com/jhlqab/p/6900798.html

flask前端与后端之间传递的两种数据格式:json与FormData:https://www.cnblogs.com/hhh5460/p/8411978.html

flask+sqlite3+echarts3+ajax 异步更新数据:https://www.cnblogs.com/hhh5460/p/6010500.html

we3cschool微信小程序API发起请求:(地址略)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值