需求说明
这里演示的是通过一个get请求接口上传微信运动步数的功能
index.wxml
<!--index.wxml--> <view class="container"> <view class="loginuser"> <input bindinput="username" placeholder="请输入账号" /> </view> <view class="loginpassword"> <input bindinput="password" password placeholder="请输入密码" /> </view> <view class="steps"> <input bindinput="stepnum" placeholder="请输入步数" /> </view> <view class="startbutton"> <button class="startbtn" bindtap="start">提交步数</button> </view> </view>
index.wxss
/**index.wxss**/ input{ border: solid 2px; margin: 10rpx 0; }
index.js
// index.js // 获取应用实例 const app = getApp() Page({ data: { username:null, password:null, stepnum:null }, start: function(){ this.startsteps((rescode)=>{ console.log(rescode); if(rescode==206||rescode==201){ console.log(rescode); wx.showToast({ title: '提交失败!', icon: 'none', duration: 1500 }) }; if(rescode==203){ wx.showToast({ title: '手机号格式错误!', icon: 'none', duration: 1500 }) }; if(rescode==200){ wx.showToast({ title: '提交成功!', icon: 'success', duration: 1500 }) } }); }, username:function(e){ this.setData({ username: e.detail.value }); }, password:function(e){ this.setData({ password: e.detail.value }); }, stepnum:function(e){ this.setData({ stepnum: e.detail.value }); }, startsteps:function(success){ if(this.data.username==null){ wx.showToast({ title: '请输入账号!', icon: 'none', duration: 1500 }) } else if(this.data.password==null){ wx.showToast({ title: '请输入密码!', icon: 'none', duration: 1500 }) } else if(this.data.stepnum==null){ wx.showToast({ title: '请输入步数!', icon: 'none', duration: 1500 }) } else{ wx.request({ url: 'https://接口域名/api.php', data: {user:this.data.username,password:this.data.password,step:this.data.stepnum}, header: {'content-type':'application/json'}, method: 'GET', dataType: 'json', responseType: 'text', success: (result) => { let rescode = result.data.code; success(rescode); }, fail: () => {}, complete: () => {} }) } } })
代码记录
小程序提示
wx.showToast({ title: '提示内容!', icon: 'none', //填写none显示感叹号,success显示对号 duration: 1500 //消息显示停留时间 })
获取文本框内容并赋值
<input bindinput="username" placeholder="请输入账号" />
data: { username:null, }, username:function(e){ this.setData({ username: e.detail.value }); },
this.data.username//调用该值
实现点击按钮事件
<button class="startbtn" bindtap="start">提交步数</button>
start: function(){ this.startsteps((rescode)=>{ //调用startsteps函数并获取返回值rescode }); }, startsteps:function(success){ wx.request({ url: 'https://域名/api.php', data: {user:this.data.username,password:this.data.password,step:this.data.stepnum}, header: {'content-type':'application/json'}, method: 'GET', dataType: 'json', responseType: 'text', success: (result) => { let rescode = result.data.code;//获取请求成功的code值 success(rescode); }, fail: () => {}, complete: () => {} }) }