目前正在学习微信小程序的开发。第一个要实现的内容当然是登录啦。所以就研究一下怎么实现传数据到服务器端然后服务器端再返回。
首先是java端
我使用的是myeclipse,创建了一个maven工程:/weserver-maven,然后再pom.xml里添加json依赖包:
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
新建一个servlet:loginTest,
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/json;charset=utf-8");//设置文件格式为json
PrintWriter out = response.getWriter();
//取得小程序传过来的数据
String nameString = request.getParameter("name") ;
String pasString = request.getParameter("pass") ;
//打印小程序传过来的数据
System.out.println(nameString) ;
System.out.println(pasString) ;
//将传过来的数据转变为json格式发送出去。
JSONArray jsonArray = new JSONArray() ;
JSONObject jsonObject = new JSONObject() ;
jsonObject.put("name", nameString) ;
jsonObject.put("pass",pasString) ;
jsonArray.add(jsonObject) ;
out.println(jsonArray);
}
把项目放在Tomcat里跑起来。
下面开始搞微信小程序端。(简单搞一搞)
//index.wxml,内容如下
<!--index.wxml-->
<view class="container">
<form bindsubmit='formSubmit'>
<input name="username" placeholder='用户名'></input>
<input name="password" placeholder='密码'></input>
<button form-type='submit'>提交</button>
</form>
<text>返回的用户名:{{returnname}}</text><br/>
<text> 返回的密码:{{returnpass}}</text>
</view>
//index.js 事件处理函数如下
//事件处理函数
formSubmit:function(e){
var _this = this ;
console.log(e.detail.value);//发送的数据
wx.request({
url: 'http://localhost:8080/weserver-maven/loginTest',
data: {
name:e.detail.value.username,//参数
pass: e.detail.value.password,//参数
},
method: 'GET',//方法为get
header: {
'content-type': 'application/json' //默认值
},
success: function (res) {//成功
console.log("收到的数据:" + res.data[0].name);//打印收到的结果res里的内容
console.log("收到的数据:" + res.data[0].pass);
_this.setData({ //设置数据
returnname: res.data[0].name,
returnpass: res.data[0].pass,
});
},
fail: function (res) {
console.log(".....fail.....");
}
})
}
最后。。结果: