Home Web Front-end JS Tutorial Use jQuery and Angular to implement login interface verification code example sharing

Use jQuery and Angular to implement login interface verification code example sharing

May 30, 2018 am 09:52 AM
angular jquery Log in

This article mainly introduces the detailed explanation of the login interface verification code using jQuery and Angular. Friends in need can refer to it. I hope it can help everyone.

Written in front:

In the previous event, I made a login function using ajax background asynchronous interaction, and I added a verification code function on it. This function The principle behind it is easy to understand, and it is also very simple to implement. I would like to share it with you. I encountered a lot of pitfalls in the process of writing it. I will write it in detail here as usual. You can use it as a reference. Friends who like it can click Like it, or follow it.

Finally achieved effect:

Before clicking to log in, it will first be judged whether the verification code is correct (the verification code does not need to be distinguished) Case sensitive (can also be case-sensitive). If the verification code is incorrect, the verification code will be refreshed. Before the verification code is verified, no cross-domain login operation will be performed.

the whole idea.

1. Take a four-digit random number

2. Assign the value to the input box of the verification code.

3. Before clicking to log in, use if to determine whether the value of the verification code input box is equal to the value of the input box. If they are equal, proceed to the next step. If they are not equal, an error will be returned directly

4. The ajax part inside can be directly inserted.

Details:

1. The background image of the verification code box here was found online. It seems that the verification code is more formal, otherwise it looks a bit low.

2. Being case-insensitive actually uses the toUpperCase() method of js to convert lowercase to uppercase. Because it is native js, it can also be used in angular!

3. Encapsulate the verification code into a function, and then call this function at the end when you click to log in. You can refresh the function every time.

4. To prevent the verification code from being copied, use: disabled="disabled" in HTML - to prevent the verification code box text from being selected.

The following is a detailed explanation of the implementation process of the code part (the comments are written in more detail):

htmlThe code should not be explained. If you don’t understand, you can leave it in the comment area ask me. There is some content about Angular below. If you haven’t learned it yet, you can skip it. It will not affect the implementation effect. (You can copy the code and try it locally.)

First let’s talk about the process of implementation using jq, and then the process of implementation in angular. Anyone who has read a few of my articles knows that I will try my best to All codes and every step are clearly commented. I hope it can help everyone.

Here is the content of html:

<p class="js5-form" id="js5-form" ng-controller="enterCtrl">
    <p id="enter-all" >
      <h3>jnshu后台登录</h3>
      <form action="" name="myForm">
        <p class="js5-input-p">
          <p class="js5-input-img1"></p>
          <input id="js5-userNum" type="text" name="userName" placeholder="用户名" maxlength="12" ng-model="userName" ng-keyup="mykey($event)" required/>
        </p>
      </form>
      <form action="" name="registerForm">
        <p class="js5-input-p">
          <p class="js5-input-img2"></p>
          <input id="js5-password" type="password" name="userPsd" placeholder="密码" maxlength="20" ng-model="userPsd" ng-keyup="mykey($event)" ng-minlength="5" ng-maxlength="16" required/>
        </p>
      </form>
      <!--账号和密码的登录框-->
      <form action="" >
        <p class="js5-input-p">
          <span class="js5-input-pSpan">验证码:</span>
          <input type="text" placeholder="不区分大小写" class="js5-form3-input" id="js5-form3-input" ng-model="writeCode" maxlength="6" ng-keyup="mykey($event)">
          <input type="text" class="js5-authCode" value="" id="js5-authCode" ng-model="showAuthCode" disabled="disabled">
           <!--disabled="disabled"禁止验证码框文字被选中-->
          <span class="spanShift" ng-click="changeVerify()">获取</span>
        </p>
      </form>
Copy after login

Here is the jq code implementation part:

var authCode;
  randomCode=$("#js5-authCode").eq(0);//获取验证码出现的方框dom
console.log(randomCode);
function createCode() {
  authCode="";//设置这个为空变量,然后往里面添加随机数
  var authCodeLength=4;//随机数的长度
  randomArray=[0,1,2,3,4,5,6,7,8,9,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;, &#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;];
  //创建一个数组,随机数从里面选择四位数或者更多
  for(var i=0;i<authCodeLength;i++){
    var index=Math.floor(Math.random()*36);//随机取一位数
    authCode +=randomArray[index];//取四位数,并+相连
  }
  console.log(authCode);//取到四位随机数之后,跳出循环
  randomCode.val(authCode);//将四位随机数赋值给验证码出现的方框
  console.log(randomCode.val());
}
//以上是封装的获取验证码的函数
$(function () {//当文档加载结束后,运行这个函数
  createCode();//一开始先运行一遍取随机数的函数
  $("#js5-btn").click(function () {//这里是一个点击事件
    console.log(window.randomCode);
    //这里写了一个必报,window.randomCode是在文档里面找到这个dom,否则上文的四个随机数传不到这里来
    var randomCode=window.randomCode.val();
    console.log(randomCode);
    var authInput=$("#js5-form3-input").val().toUpperCase(),
      user=$("#js5-userNum").val(),
      psd=$(&#39;#js5-password&#39;).val();
    //上面三个是分别获取验证码输入框的值,账号的值,密码的值。
    //验证码输入框这里,最后toUpperCase()方法是把小写转换成大写
    console.log(authInput);
    console.log(randomCode);
    console.log(user,psd);
    if (randomCode===authInput) {
    //验证验证码,在验证码输入框与验证码的值不相等之前,是不会进入下面登录的步骤的,验证码是第一步关卡
      var firstAjax = new XMLHttpRequest();
      //创建ajax对象,这里是ajax跨域的部分
      firstAjax.open("POST", "这里是你url跨域的地址", true);
      //连接服务器,跨域。
      firstAjax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      //setRequestHeader() 方法指定了一个 HTTP 请求的头部,它应该包含在通过后续 send() 调用而发布的请求中。
      //可以理解为,这是http的请求头,固定格式,位置必须要在open之后,send之前。
      firstAjax.send("name=" + user + "&pwd=" + psd);
      //在使用POST方式时参数代表着向服务器发送的数据,前面两个是账号框和密码框
      firstAjax.onreadystatechange = function () {//当参数被传入服务器的时候,引用监听事件。
        if (firstAjax.readyState == 4) {//readyState四种状态,当执行四步完成之后
          if (firstAjax.status == 200) {//返回的是200,代表成功,404未找到。
            var returnValue = JSON.parse(firstAjax.responseText);//取回由服务器返回的数据
            console.log(returnValue);
            if (returnValue.code == 0) {//这里是后端定义的,当code==0的时候,代表登录正确。
              window.location.href = "https://www.baidu.com/index.php?tn=98012088_3_dg&ch=1";
              //后端返回的数据验证成功就跳转链接。
            }
            else {
              $("#js5Message").text(returnValue.message);//当code不等于0时,返回出错信息
            }
          } else {
            alert("出错咯,咯咯咯");//返回的不是200的时候,出错。
          }
        }
      };
      createCode();//点击登录按钮,验证之后会刷新验证码
    }
    else {
      $("#js5Message").text("验证码错误,请重新输入");
      createCode();//验证码错误,刷新验证码。
    }
  })
});
Copy after login

This is the angular code implementation part:

jq part is written A little more detailed, here is quite detailed. If you don’t understand, you can go back and look at the jq part. The principles are the same. Copy it locally and try it yourself.

var enter=angular.module("myApp");
enter.controller(&#39;enterCtrl&#39;,[&#39;$scope&#39;,&#39;$http&#39;,&#39;$state&#39;,function ($scope,$http,$state) {
  $scope.changeVerify=function () {//定义了一个点击事件,获取验证码
    var authCode="";
    var authCodeLength=4;//取几个随机数字
    var randomArray=[0,1,2,3,4,5,6,7,8,9,&#39;A&#39;,&#39;B&#39;,&#39;C&#39;,&#39;D&#39;,&#39;E&#39;,&#39;F&#39;,&#39;G&#39;,&#39;H&#39;,&#39;I&#39;,&#39;J&#39;,&#39;K&#39;,&#39;L&#39;,&#39;M&#39;,&#39;N&#39;,&#39;O&#39;,&#39;P&#39;,&#39;Q&#39;,&#39;R&#39;, &#39;S&#39;,&#39;T&#39;,&#39;U&#39;,&#39;V&#39;,&#39;W&#39;,&#39;X&#39;,&#39;Y&#39;,&#39;Z&#39;];
    for(var i=0;i<authCodeLength;i++){
      var index=Math.floor(Math.random()*36);//随机取一位数
      authCode +=randomArray[index];//取四位数,并+相连
    }
    $scope.showAuthCode=authCode;//赋值
    console.log($scope.showAuthCode);
  };
  //上面是封装的获取验证码的函数,会在下面进行调用
 (function () {
    $scope.changeVerify();//调用点击事件。
    $scope.enter=function (userName,userPsd) {
      //点击登录按钮事件,将双向绑定的账号密码当做参数传入函数
      if ($scope.writeCode.toUpperCase() ==$scope.showAuthCode){//toUpperCase()将小写转化为大写
        //双向绑定验证码输入框,可以直接使用,这里是验证验证码
        $http({
          method:"POST",
          url:"你的跨域地址",//$http的固定格式
          params:{
            "name":userName,
            "pwd":userPsd
            //双向绑定的参数传到下个页面
          }
        }).then(function (res) {
          //获取服务器返回的参数
          console.log(res);
          if (res.data.code!==0){
            //参数不为0的时候,弹出提示
            alert(res.data.message);
          }else {
            //参数为0的时候,跳转页面
            $state.go("home.studentList");
          }
        })
      }else {
        alert("验证码输入错误咯,咯咯咯");
        $scope.changeVerify();//验证后,刷新验证码
      }
    }
  }());
Copy after login

Afterword

I have been writing intermittently for two days, and now I am not writing as fast as before. . That’s pretty much it. If you have any questions, please leave them in the comment area. If you have any deficiencies, you are welcome to give me some guidance and advice.

Related recommendations:

Ajax implements partial refresh login interface with verification code

js Determine the account number of the login interface Whether the password is empty

CSS3 Create a material-design style login interface example

The above is the detailed content of Use jQuery and Angular to implement login interface verification code example sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1252
29
C# Tutorial
1225
24
How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the &quot;Login&quot; button. (2) Select &quot;Retrieve Password&quot;. (3) Enter the mobile phone number you used when registering your account

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

How to install Angular on Ubuntu 24.04 How to install Angular on Ubuntu 24.04 Mar 23, 2024 pm 12:20 PM

Angular.js is a freely accessible JavaScript platform for creating dynamic applications. It allows you to express various aspects of your application quickly and clearly by extending the syntax of HTML as a template language. Angular.js provides a range of tools to help you write, update and test your code. Additionally, it provides many features such as routing and form management. This guide will discuss how to install Angular on Ubuntu24. First, you need to install Node.js. Node.js is a JavaScript running environment based on the ChromeV8 engine that allows you to run JavaScript code on the server side. To be in Ub

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the &quot;Login&quot; button and select &quot;Account and Password Login&quot;; 3. Click the &quot;Forgot your password?&quot; button; 4. Enter your account number. Click &quot;Next&quot;; 5. The system will send a verification code to your mobile phone, enter the verification code and click &quot;OK&quot;; 6. Set a new password and confirm. You can also use a third-party account (such as

How to solve the common problem of Laravel login time invalidation How to solve the common problem of Laravel login time invalidation Mar 06, 2024 pm 09:24 PM

How to solve the common problem of Laravel login time expiration When using Laravel to develop web applications, login authentication is a very important function. However, sometimes if a user does not operate for a long time after logging in, the page may automatically log out or the authentication may fail. This problem is relatively common. The following will introduce how to solve this problem by setting the session time and provide specific code examples. 1. Set the session expiration time in Laravel, by default sessi

See all articles