Home Web Front-end JS Tutorial Use Jquery to build a login page with the best user experience and remember the password automatic login function (including background code)_jquery

Use Jquery to build a login page with the best user experience and remember the password automatic login function (including background code)_jquery

May 16, 2016 pm 06:05 PM
user experience log in page

The plug-in jquery.md5.js needs to be introduced
It can run directly under IIS;
Username: Ethan.zhu
Password: 123456789
Full file download: WebApplication1_jb51.rar

First, extract the asynchronous verification of the button click event as a separate function. You need to extract the variables in the button click event and define them as global variables, and add a variable editPass (used to mark the input by yourself) Password, or password read from cookies)

Copy code The code is as follows:

var wrongTypeName, //The wrong type of the user name can be directly used as the subscript of the error message array
wrongTypePwd, //The wrong type of the user password
wrongNameHtml = new Array("", "Please enter the user name", "The username is too short", "The username exceeds 12 characters", "Your username or password is wrong", "Timeout, please log in again"),
wrongPwdHtml = new Array("", "Please enter Password", "Password length is less than 6 characters", "", "Password contains illegal characters"),
editPass=false;

Start from the button click event in the previous article :
Copy code The code is as follows:

$(".btn-submit").click (function () {
wrongTypeName = 0;
wrongTypePwd = 0;
var uname = $("#uname").val(), //Username
pwd = $("# passwd").val(), //User password
plength = pwd.length,
nlength = uname.length; //Length
if (nlength == 0)
wrongTypeName = 1;
if (nlength > 0 && nlength < 2)
wrongTypeName = 2;
if (nlength > 20)
wrongTypeName = 3;
if (plength == 0)
wrongTypePwd = 1; //Here is a judgment on the length of the username and password, and obtains the subscript of the error message array.
else {
var patrn = /^(w){6,20}$/;
if (plength < 6)
wrongTypePwd = 2;
if (plength > 50 )
wrongTypePwd = 3;
if (plength > 6 && plength < 20) {
if (!patrn.exec(pwd))
wrongTypePwd = 4; //This is for the user The front-end judges the validity of the password and returns the subscript of the error array
}
}

inputTip(0, wrongNameHtml, wrongTypeName);
inputTip(1, wrongPwdHtml, wrongTypePwd);

if (wrongTypePwd == 0 && wrongTypeName == 0) {//When the user input information is completely legal, that is, all array subscripts are 0, start executing ajax verification
//alert($. cookie("logout"));
if(editPass){
pwd = $.md5(pwd);
}
$("#passwd").val(pwd);
$("#login-form input").attr('disabled', true);
$('.remember').unbind('click');
//The information has been submitted to the server , so set all input box buttons on the page to a disabled state, which can effectively avoid repeated submissions
var remb = $('#remember-long').val();
ajaxCheck(uname, pwd, remb);
}
});

changes in lines 33 and 41. The

line is used to determine whether the password is the one the user exits to within the program. When logging in to the page, do you enter it yourself or read it from cookies? Prevent secondary encryption from causing server verification failure. The

line mainly extracts the ajax processing process, and also adds the operations of remembering the password and canceling the remembering the password after the server verification is successful, making it easier to read:
Copy code The code is as follows:

var ajaxCheck = function (uname, pwd, remb) {
$(".btn-master").addClass("visibility");
var $params = "user_name=" decodeURI (uname) "&user_pwd=" decodeURI(pwd) "&remember=" decodeURI(remb);
$.ajax({
type: 'POST',
url: 'CheckUserLogin.aspx',
//async: false,
cache: false,
dataType: 'json'
data: $params,
success: function (data, status) {
wrongTypeName = data.wrongTypeName ;
wrongTypePwd = data.wrongTypePwd;
var loginSuccess = data.loginSuccess; //Get the json data returned by the server
if (loginSuccess == 0) {
if ($('#remember- long').val() == 1) {//Remember password
$.cookie('UserName', uname, { expires: 7, path: '/' });
$.cookie( 'Password', pwd, { expires: 7, path: '/' });
}
else if ($('#remember-long').val() == 0) {//Cancel Remembered password, or no password remembered
$.cookie('UserName', null,{ expires: 7, path: '/' });
$.cookie('Password', null,{ expires: 7, path: '/' });
}
location.href = "/Members/Members.html"
}
else {
$(".btn-master ").removeClass("visibility");
$("#login-form input").attr('disabled', false);
inputTip(0, wrongNameHtml, wrongTypeName);
inputTip( 1, wrongPwdHtml, wrongTypePwd);
}
},
error: function () {
wrongTypeName = 5;
inputTip(0, wrongNameHtml, wrongTypeName);
$(" #login-form input").attr('disabled', false);
$('.remember').bind('click', function () { checkClick(); });
$( ".btn-master").removeClass("visibility");
}
})
}

When the page is initialized, the process of remembering the password must be processed :
Copy code The code is as follows:

var rememberPassword = function (logout) {//Page After loading, perform automatic login check
var ckname = $.cookie('UserName');
var ckpwd = $.cookie("Password");
if (ckname != "" && ckpwd ! = "" && ckname != null && ckpwd != null) {
$('#remember-long').val("1")
$('#remember-long').attr(' checked', true);
$("#uname").val(ckname); //Username
$('.reg-item').addClass('focus');
if (logout=="safe"){
$.cookie("logout","",{ expires: 1, path: '/' })
}
else{
$(" #passwd").val(ckpwd); //User password
$(".btn-submit").trigger('click'); //Automatic login
}
}
else {
$('#remember-long').val("0")
$('#remember-long').attr('checked', false);
}
}

var logout = $.cookie("logout");
   //Determine whether the user logs out from the inside or opens it directly
//If the user logs out from the inside, then they cannot automatically log in again Go in, unless the user refreshes the page
rememberPassword(logout);

Here is the complete new front-end script:
Copy code The code is as follows:

$(function () {

var wrongTypeName, //The wrong type of the user name, which can be directly used as the subscript of the error message array
wrongTypePwd, //The wrong user password Type
wrongNameHtml = new Array("", "Please enter the user name", "The user name is too short", "The user name is more than 12 characters long", "Your user name or password is wrong", "Timeout, please Log in again"),
wrongPwdHtml = new Array("", "Please enter password", "Password length is less than 6 characters", "", "Password contains illegal characters"),
editPass=false;

$('body').focus(); //Let the input box no longer automatically gain focus

$('.reg-action .reg-input').each(function ( ) {
var items = $(this).parent('.reg-item');
if ($(this).val()) {
items.addClass("focus");
}
$(this).bind('focus blur', function (event) {
var type = event.type; //Get the event type
if($(this).attr ("id")=="passwd"){
editPass = true;
}
if (type == 'focus') {
if (items.hasClass('error')) {
$(this).val("");
items.removeClass('error');
}
items.addClass('focus');
} else if ( !$(this).val()) {
items.removeClass('focus');
}
})
});

$(".btn- submit").click(function () {
wrongTypeName = 0;
wrongTypePwd = 0;
var uname = $("#uname").val(), //Username
pwd = $("#passwd").val(), //User password
plength = pwd.length,
nlength = uname.length; //Length
if (nlength == 0)
wrongTypeName = 1;
if (nlength > 0 && nlength < 2)
wrongTypeName = 2;
if (nlength > 20)
wrongTypeName = 3;
if (plength == 0)
wrongTypePwd = 1; //Here is a judgment on the length of the username and password, and obtains the subscript of the error message array.
else {
var patrn = /^(w){6,20}$/;
if (plength < 6)
wrongTypePwd = 2;
if (plength > 50 )
wrongTypePwd = 3;
if (plength > 6 && plength < 20) {
if (!patrn.exec(pwd))
wrongTypePwd = 4; //This is for the user The front-end judges the validity of the password and returns the subscript of the error array
}
}

inputTip(0, wrongNameHtml, wrongTypeName);
inputTip(1, wrongPwdHtml, wrongTypePwd);

if (wrongTypePwd == 0 && wrongTypeName == 0) {//When the user input information is completely legal, that is, all array subscripts are 0, start executing ajax verification
//alert($. cookie("logout"));
if(editPass){
pwd = $.md5(pwd);
}
$("#passwd").val(pwd);
$("#login-form input").attr('disabled', true);
$('.remember').unbind('click');
//The information has been submitted to the server , so set all input box buttons on the page to a disabled state, which can effectively avoid repeated submissions
var remb = $('#remember-long').val();
ajaxCheck(uname, pwd, remb);
}
});

var inputTip = function (index, tipHtml, tipNum) {
$(".reg-tip").eq(index) .html(tipHtml[tipNum]);
if (tipNum > 0)
$(".reg-item").eq(index).addClass("error");
else
$(".reg-item").eq(index).removeClass("error");
} //Define the error message page display function.Since there are only two input boxes on the page, I directly specify the index here. If there are many on the page, you can use $(this).index()

var ajaxCheck = function (uname, pwd, remb) {
$(".btn-master").addClass("visibility");
var $params = "user_name=" decodeURI(uname) "&user_pwd=" decodeURI(pwd) "&remember=" decodeURI(remb) ;
$.ajax({
type: 'POST',
url: 'CheckUserLogin.aspx',
//async: false,
cache: false,
dataType: 'json',
data: $params,
success: function (data, status) {
wrongTypeName = data.wrongTypeName;
wrongTypePwd = data.wrongTypePwd;
var loginSuccess = data. loginSuccess; //Get the json data returned by the server
if (loginSuccess == 0) {
if ($('#remember-long').val() == 1) {//Remember password
$.cookie('UserName', uname, { expires: 7, path: '/' });
$.cookie('Password', pwd, { expires: 7, path: '/' }) ;
}
else if ($('#remember-long').val() == 0) {//Cancel the remembered password, or do not remember the password
$.cookie(' UserName', null,{ expires: 7, path: '/' });
$.cookie('Password', null,{ expires: 7, path: '/' });
}
location.href = "/Members/Members.html"
}
else {
$(".btn-master").removeClass("visibility");
$("#login -form input").attr('disabled', false);
inputTip(0, wrongNameHtml, wrongTypeName);
inputTip(1, wrongPwdHtml, wrongTypePwd);
}
},
error: function () {
wrongTypeName = 5;
inputTip(0, wrongNameHtml, wrongTypeName);
$("#login-form input").attr('disabled', false);
$('.remember').bind('click', function () { checkClick(); });
$(".btn-master").removeClass("visibility");
}
})
}

var checkClick = function () {
if ($('#remember-long').attr('checked')) {
$ ('#remember-long').attr('checked', false);
$('#remember-long').val("0")
}
else {
$ ('#remember-long').attr('checked', true);
$('#remember-long').val("1")
}
}
$( '.remember').bind('click', function () { checkClick(); });
$("#remember-long").click(function () { checkClick(); });
//Remember the binding of the login checkbox and label click.

if ($.browser.msie && $.browser.version == "6.0") {
//Help Microsoft eliminate ie6
if ($.cookie('masterShow') != "hidden")
$('body').append('

Your browser is IE6.0, the vulnerability is relatively Too many, the user experience is poor, Microsoft official will give up support, for your own computer security and to obtain the best user experience, it is recommended that you upgrade to IE8.0or above or useFirefoxBrowser

< div class="m-close m-close-short">Close
Don't show anymore
');
$(".master").delay(1000).slideDown('', function () {
$(".m-close").fadeIn();
});
$(".m-close-short").click(function () {
$(".m-close").fadeOut('', function () {
$(".master") .slideUp();
});
});
$(".m-close-long").click(function () {
$(".m-close") .fadeOut('', function () {
$(".master").slideUp();
$.cookie('masterShow', 'hidden');
});
});
}

var rememberPassword = function (logout) {//Perform automatic login check after the page is loaded
var ckname = $.cookie('UserName');
var ckpwd = $.cookie("Password");
if (ckname != "" && ckpwd != "" && ckname != null && ckpwd != null) {
$('#remember-long' ).val("1")
$('#remember-long').attr('checked', true);
$("#uname").val(ckname); //Username
$('.reg-item').addClass('focus');
if (logout=="safe"){
$.cookie("logout","",{ expires: 1, path: '/' })
}
else{
$("#passwd").val(ckpwd); //User password
$(".btn-submit") .trigger('click'); //Automatic login
}
}
else {
$('#remember-long').val("0")
$(' #remember-long').attr('checked', false);
}
}

var logout = $.cookie("logout");//Determine whether the user is from within Exit
rememberPassword(logout);

$(document).bind('keydown', 'return', function () { $(".btn-submit").trigger('click') ; });
})

Regarding the background program involved in the page, I used page-level aspx, of course you can also use ashx to handle it. This background processing is responsible for verifying whether the password is correct and setting the session value if the user logs in correctly. If you need to demonstrate, you can define constants in the background to make verification judgments:
Copy Code The code is as follows:

Hashtable ht = new Hashtable();
string uname = Request.Params["user_name"];
string pwd = Request.Params["user_pwd"];
int wrongTypeName = 0;
int wrongTypePwd = 0;
uname = PageValidate.InputText(uname, 30);

if (Validator.StrIsNullOrEmpty(uname))
{
wrongTypeName = 1;
}
if (Validator.StrIsNullOrEmpty(pwd))
{
wrongTypePwd = 1;
}
if (!string.IsNullOrEmpty(uname) && !string.IsNullOrEmpty(pwd ))
{
//The following constants are used for demonstration:
string userName="ethan.zhu";
string password="";//The string after MD5 encryption is required
if (uname==userName&&password==pwd )
ht.Add("loginSuccess", 0);
else
wrongTypeName = 4;//Return username or password error

if (wrongTypeName > 0 || wrongTypePwd > 0)
{
ht.Add("wrongTypeName", wrongTypeName);
ht.Add("wrongTypePwd", wrongTypePwd);
}
Response.Write(CreateJsonParams(ht));
}
Response.End();
}

Convert Hashtable to json:
Copy code The code is as follows:

public static string CreateJsonParams(Hashtable items)
{
string returnStr = "";
foreach (DictionaryEntry item in items)
{
returnStr = """ item.Key.ToString() "":"" item.Value.ToString() "",";
}
return "{" returnStr.Substring(0, returnStr.Length - 1) "}";

}
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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Understand the user experience differences between vivox100s and x100 Understand the user experience differences between vivox100s and x100 Mar 23, 2024 pm 05:18 PM

With the continuous development of science and technology, people's requirements for communication equipment are also constantly increasing. In the market, Vivox100s and X100 are two mobile phone brands that have attracted much attention. They all have unique characteristics and each has its own advantages. This article will compare the user experience differences between these two mobile phones to help consumers better understand them. There are obvious differences in appearance design between Vivox100s and X100. Vivox100s adopts a fashionable and simple design style, with a thin and light body and comfortable hand feel; while X100 pays more attention to practicality

Why do some people think Android photography can beat Apple? The answer is so direct Why do some people think Android photography can beat Apple? The answer is so direct Mar 25, 2024 am 09:50 AM

When discussing the camera function of Android phones, most users give it positive feedback. Compared with Apple phones, users generally believe that Android phones have better camera performance. This view is not unfounded, and the practical reasons are obvious. High-end Android phones have greater competitive advantages in terms of hardware configuration, especially camera sensors. Many high-end Android phones use the latest, top-of-the-line camera sensors, which are often more outstanding than iPhones released at the same time in terms of pixel count, aperture size, and optical zoom capabilities. This advantage enables Android phones to provide higher-quality imaging effects when taking photos and recording videos, meeting users' needs for photography and videography. Therefore, the competitive advantage of hardware configuration has become the attraction of Android phones.

Xiaomi Auto APP tops Apple's App Store free list with official sales of nearly 90,000 Xiaomi Auto APP tops Apple's App Store free list with official sales of nearly 90,000 Apr 01, 2024 am 09:56 AM

On March 31, CNMO noticed that the Xiaomi Auto mobile application topped the Apple App Store free application rankings on March 31. It is reported that Xiaomi Auto’s official App has won the favor of the majority of users with its comprehensive functions and excellent user experience, quickly ranking first in the list. This much-anticipated Xiaomi Auto App not only realizes seamless connection of the online car purchase process, but also integrates remote vehicle control services. Users can complete a series of intelligent operations such as vehicle status inquiry and remote operation without leaving home. Especially when the new model of Xiaomi Motors SU7 is released, the App is launched simultaneously. Users can intuitively understand the configuration details of SU7 through the App and successfully complete the pre-order. Xiaomi Auto App internal design

ViewSonic debuts at ChinaJoy2024 with stunning 8K large screen ViewSonic debuts at ChinaJoy2024 with stunning 8K large screen Jul 24, 2024 pm 01:33 PM

From July 26th to July 29th, the annual ChinaJoy2024 will be grandly opened at the Shanghai New International Expo Center. ViewSonic will join hands with ZOL Zhongguancun Online to create a full coverage of vision, hearing, and touch for users and game enthusiasts. A technological feast. ZOL Zhongguancun Online is an IT interactive portal that covers the entire country and is positioned to promote sales. It is a composite media that integrates product data, professional information, technology videos, and interactive marketing. Zhongguancun Online broke the dimensional wall and appeared at booth S101 of Hall E7 of ChinaJoy with the theme of "Trendy and Fun", bringing a diverse and immersive exhibition experience to audiences and industry insiders from around the world. ViewSonic Exhibition Area: Explore high-end display technology 1

What are the five elements of user experience? What are the five elements of user experience? Aug 26, 2022 pm 05:24 PM

Five elements of user experience: 1. User needs, what users and operators want to get from this product; 2. Scope of functions, what functions does this product have; 3. Process design, which can be divided into two major categories: interaction design and information architecture. In this part, interaction design describes "possible user behavior", and information architecture focuses on how to express information to users; 4. Prototyping design, deciding where interactive elements such as a section or button should be placed on the page; 5. Perceptual design, It is the bringing together of content, functionality and aesthetics to produce a final design that meets all objectives on other levels.

Best Plugins for php CodeIgniter: Take your website to the next level Best Plugins for php CodeIgniter: Take your website to the next level Feb 19, 2024 pm 11:48 PM

CodeIgniter is a powerful PHP framework, but sometimes you may need additional features to extend its capabilities. Plugins can help you achieve this. They can provide a variety of functions, from improving website performance to improving security. 1.HMVC (Hierarchical Model View Controller) Hmvc plugin allows you to use layered MVC architecture in CodeIgniter. This is useful for large projects with complex business logic. Using HMVC you can organize controllers into different modules and load and unload these modules as needed. Demo code: //Add the following code in config/routes.php: $route["/module/contr

Analyzing Vue's server-side communication process: how to improve user experience Analyzing Vue's server-side communication process: how to improve user experience Aug 10, 2023 am 11:19 AM

Analyzing Vue's server-side communication process: How to improve user experience Introduction: With the rapid development of the Internet, communication between the client and the server has become increasingly important. As a modern JavaScript framework, Vue provides developers with a wealth of tools and technologies to implement server-side communication. This article will delve into Vue's server-side communication process and introduce some tips and best practices to improve user experience. 1. Overview of Vue server-side communication process Vue’s server-side communication process includes the following key steps

DXO: Huawei Mate60 Pro screen test score 143 has significantly improved DXO: Huawei Mate60 Pro screen test score 143 has significantly improved Mar 22, 2024 pm 06:31 PM

On March 21, CNMO noticed that DXOMARK announced the screen test results of Huawei Mate60Pro, with a score of 143 points, ranking in the middle of the global screen rankings. According to DXOMARK's review, the device's screen provides a comfortable user experience. Compared with the previous generation Huawei Mate50Pro, the latest version of the screen has significant improvements in motion and touch response and artifact management, allowing users to enjoy a better visual experience. The readability of the screen basically maintains the level of the previous generation product. Although the brightness in low-light environments is slightly insufficient, the screen of the device has good readability and accurate color rendering in most ambient light conditions. The readability is quite good especially outdoors, and the screen brightness reaches

See all articles