微信小程序与java后台数据交互
先到 官网 申请账号和下载 微信开发工具。
进入微信开发工具,index.wxml关键代码入下:
<view class="usermotto"> <text class="user-motto">{{motto}}</text> </view> <view> <button bindtap='change'>变更</button> </view>
index.js关键代码如下:
get提交方式:
change: function () { var that = this; wx.request({ url: 'http://localhost:8080/myTest/wxxcx/wxlogin.do', method: 'get', data: { pass: 'text', name: '测试11' }, header: { 'content-type': 'application/json' }, success: function (res) { that.setData({ motto: res.data[0].name }); }, fail: function (err) { console.log("sssssssssssss" + err.data); } }) },
post提交方式:
change: function(){ var that = this; wx.request({ url: 'http://localhost:8080/myTest/wxxcx/wxlogin.do', method:'post', data:{pass:'text',name:'测试11'}, header: { 'content-type': 'application/x-www-form-urlencoded' //post提交方式这里json需改成这个x-www-form-urlencoded,否则后台接收不到数据,原因参考:http://blog.csdn.net/mhmyqn/article/details/25561535/ }, success: function(res){ that.setData({ motto: res.data[0].name }); }, fail:function(err){ console.log("sssssssssssss"+err.data); } }) }
java后台关键代码:
@RequestMapping(value = "wxlogin.do") public String wxlogin(String name,HttpSession session, HttpServletRequest req, HttpServletResponse resp, Model model) { resp.setContentType("text/json"); resp.setCharacterEncoding("utf-8"); String pass = (String) req.getParameter("pass"); log.info("pass==" + pass + ",name=" + name); PrintWriter pw = null; Map map = new HashMap(); map.put("pass", pass); map.put("status", "进入后台了"); map.put("name", name); JSONArray json = JSONArray.fromObject(map); try { pw = resp.getWriter(); pw.print(json); } catch (IOException e) { log.info(e); log.error(e); e.printStackTrace(); } finally { if (pw != null) pw.close(); } return null; }
定义了个内容变更按钮
调试界面如下:
单击变更内容后,java后台输出:
微信开发工具调试界面
数据交互成功:
需要注意一点,微信开发工具wx.request要调用本地localhost项目,需在微信项目开发工具项目设置里勾选不校验合法域名。。。选项
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。