后台程序返回了数据后,第三步就是小程序该怎么接收返回数据并进行相关业务逻辑处理。
小程序接收返回数据。Python-Flask向小程序返回了JSON格式的数据后,小程序的wx.requset()函数里的SUCESS回调函数用来处理返回数据。下面贴下项目中wx.requset()函数中sucess回调函数。
wx.request({
url: 'https://我的后台服务器网址/score',
data: {
acc_nbr:JSON.stringify(acc_nbr),
grade1: JSON.stringify(grade1), //将数据格式转为JSON
grade2: JSON.stringify(grade2), //将数据格式转为JSON
grade3: JSON.stringify(grade3), //将数据格式转为JSON
txt1:JSON.stringify(txt1),
txt2:JSON.stringify(txt2),
txt3:JSON.stringify(txt3)
},
method: "POST",
header: {
'content-type': 'application/x-www-form-urlencoded',
'chartset': 'utf-8'
},
success: function (res) {
console.log(res.data);
wx.showToast({
title: res.data,//这里打印出登录成功
icon: 'success',
duration: 1000
});
var acc_nbr = that.data.phoneNum;
wx.redirectTo({
url: '../graderesult/graderesult?phoneNum=' + acc_nbr
})
}
})
代码详解:单独拿出sucess回调函数讲解。
success: function (res) {
console.log(res.data);
wx.showToast({
title: res.data,//这里打印出登录成功
icon: 'success',
duration: 1000
});
var acc_nbr = that.data.phoneNum;
wx.redirectTo({
url: '../graderesult/graderesult?phoneNum=' + acc_nbr
})
}
res入参存储的数据,即res.data,就是第二步后台返回的数据。可以用console.log(res.data)看下返回的数据是否正确。
我的项目在拿到后台返回的数据,进行了弹窗展示返回数据wx.showToast和页面的跳转wx.redirectTo,大家可以根据自己的业务需求在sucess回调函数编写自己的业务逻辑。
结尾:
至此,微信小程序和Python后台交互数据的步骤已经讲完。正如文章开头所讲,学过ajax的同学读完会发现微信小程序与后台交互数据非常像ajax,所以,文章结尾贴出一个彩蛋,即神奇的ajax代码,出自我的另一个web项目,供大家品鉴^_^~