零基础学小程序005---小程序登陆注册功能实现

时间:2022-07-28
本文章向大家介绍零基础学小程序005---小程序登陆注册功能实现,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

上一节虽然有提到小程序用户注册与登陆功能,但是篇幅有限,就没详细写。今天就来给大家详细讲解下小程序的注册与登陆功能实现。

不多说,先看效果图

▲小程序登陆与注册实现

先说下登陆和注册的基本原理

"

登陆和注册,肯定需要我们获取输入的用户名和密码。然后把用户名和密码传到服务器后台,后台把用户名和密码存到数据库里,存入成功就返回注册成功的信息, 以后登陆时就可以直接查询用户是否存在,存在就比对密码,如果密码一致,就返回登陆成功的信息。

"

本节实现功能点

  • 获取输入内容
  • 注册功能
  • 登陆功能

下面就逐个功能点给大家讲解。

获取输入内容

先看下布局index.xml

<!--index.wxml-->

<input class='inputA' placeholder="请输入用户名" bindinput="inputName" />

<input class='inputA' placeholder="请输入密码" password='true' bindinput="inputPassword" />

<button wx:if="{{!isLogin}}" type='primary' bindtap='register'>注册</button>

<button wx:if="{{isLogin}}" type='primary' bindtap='login'>登陆</button>

注意点:

  • bindinput="inputName" 中的inputName对应index.js里的inputName()函数,用来获取输入的用户名
  • bindinput="inputPassword" 中的inputPassword对应index.js里的inputPassword()函数,用来获取输入的用户名 下面贴出这两个函数
 //获取用户输入的值a
inputName: function(e) {
 inputName = e.detail.value;
}, //获取用户输入的值b
inputPassword: function(e) {
 inputPassword = e.detail.value;
   console.log("输入的密码:" + inputPassword);
},

到这里我们就可以获取到输入的用户名和密码了。

接下来,需要对输入的用户名和密码做校验

注意校验用户名不能为空,密码不能为空,密码不能少于6位数。 校验代码如下:

 //检测输入值
checkInput: function() {
   if (inputName == "" || inputName == null ||
  inputName == undefined) {
      this.showErrorToastUtils('请输入用户名');
 } else if (inputPassword == "" || inputPassword == null || inputPassword == undefined) {
         this.showErrorToastUtils('请输入密码');
 } else if (inputPassword.length < 6) { 
           this.showErrorToastUtils('密码至少要6位');
 } 
  return true;
},

当用户名和密码都符合规则时,返回true。说明输入的用户名和密码合法。

注册功能

注册就需要我们请求后台注册接口了。

 // 注册
register: function() {
   var that = this; 
    var isrightful = that.checkInput();
 if (isrightful) {
  wx.request({
     url: 'http://localhost:8080/user/testSave',
     header: {     "Content-Type": "application/x-www-form-urlencoded"
    },    
     method: "POST",    
    data: {
          name: inputName, 
          password: inputPassword
   },    
    success: function(res) {
       console.log(res);
       if (res.statusCode != 200) {
             wx.showToast({ //这里提示失败原因
              title: res.data.message,       
              icon: 'loading',     
              duration: 1500
     })
    } else {
     wx.showToast({
       title: '注册成功', //这里成功
      icon: 'success',
       duration: 1000
     });
     that.setData({
          isLogin: true,
     }
     )
    }
   }, 
    fail: function(res) {
      console.log(res)
     wx.showToast({      
          title: '请求失败',      
          icon: 'none',      
          duration: 1500
    })
   }
  });
 }
},

注意点: if (res.statusCode != 200) 这里我们判断后台返回的statusCode,只有statusCode等于200时,才说明我们注册成功,下面时注册成功后后台返回的信息

▲注册成功

登录功能

登陆其实和注册都是把用户名和密码传到后台,只不过登陆时,先那用户名去数据库里查,看是否存在这个用户。

如果存在,就去比对我们传的密码和数据库里存的密码是否一样,如果一样就登陆成功,返回登陆信息。

到此我们的小程序注册与登陆功能就实现了。