微信小程序之json数据处理
开发环境:微信开发者工具+eclipse+Tomcat+Mysql
功能描述:数据库返回给微信小程序前台一个对象的信息,前台要对该对象的信息处理,将该对象的各个属性值显示在wxml页面中。
困扰所在:后台返回给前台的是一个对象,前台不能直接获取该对象的各个属性值。
解决:将java对象转换成Json字符串,前台对json字符串解析,获取各个属性的值。
首先eclipse中要引入以下几个jar包,处理json数据
下面是在eclipse中的一个servlet文件,student是创建的学生类
public class StudentServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST");
String account = request.getParameter("account");
StudentDao sd=new StudentDao();
Student stu=sd.findBySno(account);
//以Json形式返回给微信小程序
JSONObject json=JSONObject.fromObject(stu);
String strJson=json.toString();
Writer out = response.getWriter();
out.write(strJson);
out.flush();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
这样返回给小程序前台的就是json格式的数据,前台通过如下解析取值
mine_student.js
wx.request({
url:'http://localhost:8080/GraduateDesign/StudentServlet', data: {
account
},
method: 'GET',
header: {
'content-type': 'json' // 默认值
},
success: function (res) {
//回调函数中的携带服务器响应数据
that.setData({
sname: res.data.sname,
ssex: res.data.ssex,
scollage: res.data.scollage,
sinstitute: res.data.sinstitute,
smajor: res.data.smajor,
pwd: res.data.spwd
})
},
fail: function (res) {
console.log("fail to connect");
}
})
js中获取的数据库中的值解析后传给wxml页面,显示如下:
至此,成功将数据库中的信息传回到前台。