servlet后端连接 微信小程序与_微信小程序与java后台数据交互

本文介绍了如何使用微信小程序与Java后端进行数据交互。通过在微信开发工具中设置指数代码和方法,分别展示了GET和POST请求的实现。在Java后台,使用了servlet处理来自小程序的请求,并返回响应数据。在实际操作中,需要注意微信开发工具的域名配置以确保本地调试能正常进行。
摘要由CSDN通过智能技术生成

先到 官网 申请账号和下载 微信开发工具。

进入微信开发工具,index.wxml关键代码入下:

{{motto}}

变更

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项目,需在微信项目开发工具项目设置里勾选不校验合法域名。。。选项

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值