Ajax asynchronous way to implement login and authentication _ajax related

Source: Internet
Author: User
Tags button type eval

This article describes the Ajax asynchronous way to achieve login and verification of the detailed code, to share with you for your reference. Specifically as follows:

Login Code

This is implemented using the BOOTSTRAP3 component functionality.

<div class= "Login_con_r" >  

Code for asynchronous login requests

<script> $ (function () {var btnlogin = $ (' #loginBtn ');
    var form = $ (' #loginFormId ');
      $ (' body '). KeyDown (function (e) {if (E.keycode = =) {Dologin ();
    }
    });
    Btnlogin.on (' click ', Function () {dologin ();

    });
      var dologin = function () {var usernameelement = $ ("#j_username");
      var passwordelement = $ ("#j_password");
      var username = Usernameelement.val ();
      var password = passwordelement.val (); if (!
      Validation.notnull ($ (' body '), usernameelement, username, ' username cannot be empty ') {return false; } if (!
      Validation.notnull ($ (' body '), passwordelement, password, ' Password cannot be empty ') {return false;
      } btnlogin.attr (' disabled ', ' disabled '). HTML (' login ... ');
      var param = form.serialize ();
        $.ajax ({url:contextpath+ "/login.koala", DataType: "JSON", Data:param, type: "POST", Success:function (data) {if (data.success) {$ ('. LogIn_con_r '). Message ({type: ' Success ', Content: ' Login successful!
            '
            });
          /* The asynchronous request used here, when the request login success, reposition to the index interface * * window.location.href=contextpath+ "/index.koala";
            }else{btnlogin.removeattr (' disabled '). HTML (' login ');
          $ ('. Login_con_r '). Message ({type: ' Error ', content:data.errorMessage});
    }
        }
      });
    }; 

  });

 </script>

Validation JS code to use Validation.js

Validator = {Require: {expression:/.+/,errormsg: "This field cannot be empty"}, Email: {expression:/^\w+ ([-+.] \w+) *@\w+ ([-.] \\w+) *\.\w+ ([-.] \w+) *$/,errormsg: "Email format is not correct"}, mobile:{expression:/^ (1[3|5|8]{1}\d{9}) $/,errormsg: "Mobile phone format is not correct"}, telephone:{ expression:/^ ((0\d{2,3}-)? \d{7,8} (-\d{4})) $/,errormsg: "The phone number format is not correct"}, idcard:{expression:/^\d{15} (\d{2}[a-za-z0-9])? $/,ERRORMSG: "ID card number is malformed"}, number:{ Expression:/^-? (\d+| [1-9]\d*\.\d+|0\.\d*[1-9]\d*|0?\.0+|0) $/,errormsg: "Support only Numbers"}, English:{expression:/^[a-za-z]+$/,errormsg: "Only English characters are supported "}, Chinese:{expression:/^[\u0391-\uffe5]+$/,errormsg:" Only Chinese characters are supported}, url:{expression:/^http:\/\/[a-za-z0-9]+\.[ a-za-z0-9]+[\/=\?%\ -&_~ ' @[\]\ ': +!] * ([^<>\ "\"]) *$/,errormsg: "Malformed URL address"}, Regex:{errormsg: "Malformed"}, UnSafe:/^ ([a-z]*|[ a-z]*|\d*| [-_\~!@#\$%\^&\*\.\ (\) \[\]\{\}<>\?\\\/\ ' \ "]*) |. {0,5}) $|\s/, Issafe:function (str) {return!this. Unsafe.test (str);}, safestring: {expression: "this. Issafe (value), ErrorMsg: "Support only Chinese Characters"}, Erroritem: [docuMent.forms[0]], errormessage: ["The following reasons cause the commit failure: \t\t\t\t"], validate:function (theform, mode) {var obj = theform | | e
    Vent.srcelement;
    var count = obj.elements.length; This.
    Errormessage.length = 1; This.
    Erroritem.length = 1; This.
    Erroritem[0] = obj;
        for (Var i=0;i<count;i++) {with (Obj.elements[i]) {if (disabled) continue;
        var _datatype = getattribute ("DataType");
        if (typeof (_datatype) = = "Object" | | | typeof (This[_datatype]) = = "undefined") continue; This.
        Clearstate (Obj.elements[i]);
        if (GetAttribute ("require") = = "false" && value = = "") continue; var errormsg = getattribute ("ErrorMsg")?
        GetAttribute ("ErrorMsg"): this[_datatype].errormsg; errormsg = ErrorMsg | |
        "Invalid";
        var validateexpr = getattribute ("validateexpr"); validateexpr = validateexpr | |
        This[_datatype].expression;
  Switch (_datatype) {case ' Date ': Case ' Repeat ': Case ' Range ':        Case ' Compare ': Case ' Custom ': Case ' Group ': Case ' Limit ': Case ' Limit B ": Case" safestring ": if (!eval (validateexpr)) {this.
            Adderror (i, errormsg);
          } break; Default:if (!eval (validateexpr). Test (value) {this.
            Adderror (i, errormsg);
        } break; }} if (this. Errormessage.length > 1) {var content = this.
      Errormessage[1].replace (/\d+:/, ""); var $element = $ (this.
      ERRORITEM[1]);
      var name = $element. attr (' name '); if (Name.indexof (' DTO ')!=-1) {name = Name.split ('. ')
      [1];
      var $targetElement = $element;
      var $tempElement = $targetElement. Closest (' form '). Find (' # ' + name + ' ID ');
      if ($tempElement. Hasclass (' select ')) {$targetElement = $tempElement;
      } showerrormessage ($element. Closest ('. Modal '), $targetElement, content); Return false;
  return true;
    }, Limit:function (Len,min, max) {min = min | | 0; max = Max | |
    Number.MAX_VALUE;
  return min <= len && len <= Max;
  }, Lenb:function (str) {return str.replace (/[^\x00-\xff]/g, "* *"). Length;
      }, Clearstate:function (Elem) {with (Elem) {if (Style.color = = "Red") Style.color = "";
      var ligertipid = getattribute ("Ligertipid");
        if (ligertipid && ligertipid!= "") {removeattribute ("ligertipid");
      $ (elem). Ligerhidetip (); }}, Adderror:function (index, str) {this. Erroritem[this. Erroritem.length] = this.
    Erroritem[0].elements[index]; This. Errormessage[this. Errormessage.length] = this.
  Errormessage.length + ":" + str;
  }, Exec:function (OP, Reg) {return new REGEXP (Reg, "G"). Test (OP);
      }, Compare:function (OP1,OPERATOR,OP2) {switch (operator) {case ' notequal ': Return (OP1,!= OP2); Case "GreaterThan": Return (OP1 > OP2);
      Case "Greaterthanequal": Return (OP1 >= OP2);
      Case "LessThan": Return (OP1 < OP2);
      Case "Lessthanequal": Return (OP1 <= OP2);
    Default:return (OP1 = = OP2);
    }, Mustchecked:function (name, Min, max) {var groups = Document.getelementsbyname (name);
    var haschecked = 0; min = Min | |
    1; max = Max | |
    Groups.length;
    for (Var i=groups.length-1;i>=0;i--) if (groups[i].checked) haschecked++;
  return min <= haschecked && haschecked <= Max; }, Isdate:function (OP, formatstring) {formatstring = formatstring | |
    "Ymd";
    var m, year, month, day; Switch (formatstring) {case "Ymd": M = Op.match (New RegExp ^\\s* ((\\d{4}) | (
        \\D{2})) ([-./]) (\\d{1,2}) \\4 (\\d{1,2}) \\s*$));
        if (M = = null) return false;
        Day = m[6];
        month = m[5]--; Year = (M[2].length = 4)?
        M[2]: getFullYear (parseint (m[3), 10));
      Break CASE "dmy": M = Op.match (New RegExp ("^\\s* (\\d{1,2}) ([-./]) (\\d{1,2}) \\2 ((\\d{4}) | (
        \\D{2})) (\\s*$));
        if (M = = null) return false;
        Day = m[1];
        month = m[3]--; Year = (M[5].length = 4)?
        M[5]: getFullYear (parseint (m[6), 10));
      Break
    Default:break;
    var date = new Date (year, month, day); return (typeof date = = "Object" && year = = Date.getfullyear () && month = = Date.getmonth () && Day
    = = Date.getdate ()); function getFullYear (y) {return (y<30?)
  "A": "") + y) |

}
}; var Validation = {notnull:function ($container, $element, content, errormessage) {if (IsNull (content)) {Sho
      Werrormessage ($container, $element, errormessage);
    return false;
  return true; }, Email:function ($container, $element, content, errormessage) {var reg = new RegExp (/^ (\w) + (\.\w+) *@ (\w) + (\.\w{2
    , 3}) {1,3}) $/); if (!reg.test (content)) {Showerrormessage ($containEr, $element, errormessage);
    return false;
  return true;
    }, Serialnmuber:function ($container, $element, content, errormessage) {var reg = new RegExp (/^[0-9a-za-z_-]*$/);
      if (!reg.test (content)) {showerrormessage ($container, $element, errormessage);
    return false;
  return true;
    }, Number:function ($container, $element, content, errormessage) {var reg = new RegExp (/^[0-9]*$/);
      if (!reg.test (content)) {showerrormessage ($container, $element, errormessage);
    return false;
  return true; }, Humanname:function ($container, $element, content, errormessage) {var reg = new RegExp (/(^[a-z a-z]*$) | (
    ^[\u4e00-\u9fa5]*$)/);
      if (!reg.test (content)) {showerrormessage ($container, $element, errormessage);
    return false;
  return true;
    }, Checkbyregexp:function ($container, $element, REGEXP, content, errormessage) {var reg = new RegExp (REGEXP); if (!reg.test (content)) {ShoWerrormessage ($container, $element, errormessage);
    return false;
  return true;

}
}; /** * Check for empty/var isNull = function (item) {if (item = NULL | | item = = "" | | Item.replace (/(^\s*) | (
  \s*$)/g, "") = = "") {return true;
return false;

}; /** * Display hint info/var showerrormessage = function ($container, $element, content) {$element. popover ({Content:conten T, trigger: ' Manual ', Container: $container}). PopOver (' Show '). On ({' Blur ': function () {$element. P
        Opover (' Destroy ');
      $element. Parent (). Removeclass (' Has-error ');
        }, ' KeyDown ': function () {$element. PopOver (' destroy ');
      $element. Parent (). Removeclass (' Has-error ');
). focus (). Parent (). addclass (' Has-error ');
 };

I hope this article will help you with your learning.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.