1.数据的双向绑定
前面学习了数据的单向绑定,从js改变前端页面的数据,那我们想让前端的数据到后台怎么变呢?
这里就不得不提到组件的bindinput
键盘输入时触发,event.detail = {value, cursor, keyCode},keyCode 为键值,2.1.0 起支持,处理函数可以直接 return 一个字符串,将替换输入框的内容。
wxml
<view>输入:{{phone}}</view>
<input placeholder="请输入手机号" value="{{phone}}" bindinput="macthPhone"></input>
js
macthPhone: function(e) {
this.setData({
phone: e.detail.value,
})
},
输入内容,触发macthPhone事件,自动进行值的修改
2.登录页面实现(前后端交互)
在微信小程序中,自然也存在前后端的交互问题,当我们需要发起请求时,可以调用微信自带API:wx.request
。前端使用微信小程序进行编写,后端使用任何后端语言皆可。
wx.request({
url: 'url', //开发者服务器接口地址
data: data, //请求参数
dataType: dataType, //返回的数据格局(json,其他)
enableCache: true, //开启 cache
enableHttp2: true, //开启 http2
enableQuic: true, //开启 quic
header: header, //设置请求的 header,header 中不能设置 Referer。`content-type` 默认为 `application/json`
method: method, //HTTP请求方式(OPTIONS、GET、HEAD、POST、PUT、DELETE、TRACE、CONNECT
responseType: responseType, //响应的数据类型(text, arraybuffer)
timeout: 0, //超时时间,单位为毫秒
success: (result) => {}, //接口调用成功的回调函数
fail: (res) => {}, //接口调用失败的回调函数
complete: (res) => {}, //接口调用结束的回调函数(调用成功、失败都会执行)
})
但是在微信小程序中,只允许固定且注册的域名发出请求,如果我们需要在本地今天调试,那么进行如下操作。
wxml
<view>输入:{{phone}}</view>
<input placeholder="请输入手机号" value="{{phone}}" bindinput="macthPhone"></input>
<view>验证码: <text>点击获取验证码</text></view>
<input value="{{code}}" bindinput="macthCode" placeholder="请输入验证码"></input>
<button bindtap="login">登录</button>
js
Page({
/**
* 页面的初始数据
*/
data: {
phone : '',
code : '',
},
login: function() {
var that = this;
//发出请求
wx:wx.request({
url: 'http://localhost:8080/_war/login',
data: {
phone: that.data.phone,
code: that.data.code},
enableCache: true,
enableHttp2: true,
enableQuic: true,
method: "GET",
responseType: "Text",
timeout: 0,
success: (result) => {
console.log(result)
},
fail: (res) => {},
complete: (res) => {},
})
},
macthPhone: function(e) {
this.setData({
phone: e.detail.value,
})
},
macthCode: function(e) {
this.setData({
code: e.detail.value,
})
},
})
后端代码
@Controller
public class Login {
@RequestMapping("/login")
@ResponseBody
public String login(String phone, String code) {
System.out.println("phone:" + phone);
System.out.println("code:" + code);
return "success";
}
}