Home  >  Article  >  Web Front-end  >  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

WBOY
WBOYOriginal
2016-05-16 18:05:051880browse

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:
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
Previous article:How jquery calls wcf and displays data_jqueryNext article:How jquery calls wcf and displays data_jquery

Related articles

See more