欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ajax异步方式实现登录与验证

程序员文章站 2022-06-03 15:10:21
本文实例讲述了ajax异步方式实现登录与验证的详细代码,分享给大家供大家参考。具体如下: 登录代码 这个是使用bootstrap3的组件功能实现的

本文实例讲述了ajax异步方式实现登录与验证的详细代码,分享给大家供大家参考。具体如下:

登录代码

这个是使用bootstrap3的组件功能实现的

<div class="login_con_r">
      <h4>登录</h4>
      <form id="loginformid" class="form-horizontal" action="login" method="post">
        <div class="form-group input-group">
          <span class="input-group-addon"><span class="glyphicon glyphicon-user"></span></span>
          <input type="text" class="form-control" placeholder="用户名" name="username" id="j_username" value="koala">
        </div>
        <div class="form-group input-group">
          <span class="input-group-addon"><span class="glyphicon glyphicon-lock"></span></span>
          <input type="password" name="password" id="j_password" class="form-control" placeholder="密码" value="888888"/>
        </div>       
        <div class="form-group input-group" style="margin-top: 45px;">
          <button type="button" class="btn btn-primary btn-block" id="loginbtn">登录</button>
        </div>
      </form>
    </div>

异步登录请求的代码

<script>
  $(function(){
    var btnlogin = $('#loginbtn');
    var form = $('#loginformid');
    $('body').keydown(function(e) {
      if (e.keycode == 13) {
        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, '用户名不能为空')) {
        return false;
      }
      if (!validation.notnull($('body'), passwordelement, password, '密码不能为空')) {
        return false;
      }
      btnlogin.attr('disabled', 'disabled').html('正在登录...');
      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: '登录成功!'
            });
            /*这里使用的异步请求,当请求登录成功的时候,重新定位到index界面*/
            window.location.href=contextpath+"/index.koala";
          }else{
            btnlogin.removeattr('disabled').html('登录');
            $('.login_con_r').message({
              type: 'error',
              content: data.errormessage
            });
          }
        }
      });
    };
    }); 

  </script>

使用到的验证js代码validation.js

validator = {
  require : {expression:/.+/,errormsg:"该字段不能为空"},
  email : {expression:/^\w+([-+.]\w+)*@\w+([-.]\\w+)*\.\w+([-.]\w+)*$/,errormsg:"email格式不正确"},
  mobile:{expression:/^(1[3|5|8]{1}\d{9})$/,errormsg:"手机格式不正确"},
  telephone:{expression:/^(((0\d{2,3}-)?\d{7,8}(-\d{4})?))$/,errormsg:"电话号码格式不正确"},
  idcard:{expression:/^\d{15}(\d{2}[a-za-z0-9])?$/,errormsg:"身份证号码格式不正确"},
  number:{expression:/^-?(\d+|[1-9]\d*\.\d+|0\.\d*[1-9]\d*|0?\.0+|0)$/,errormsg:"仅支持数字"},
  english:{expression:/^[a-za-z]+$/,errormsg:"仅支持英文字符"},
  chinese:{expression:/^[\u0391-\uffe5]+$/,errormsg:"仅支持中文字符"},
  url:{expression:/^http:\/\/[a-za-z0-9]+\.[a-za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,errormsg:"url地址格式不正确"},
  regex:{errormsg:"格式不正确"},
  unsafe : /^(([a-z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
  issafe : function(str){return !this.unsafe.test(str);},
  safestring : {expression:"this.issafe(value)",errormsg:"仅支持中文字符"},
  erroritem : [document.forms[0]],
  errormessage : ["以下原因导致提交失败:\t\t\t\t"],
  validate : function(theform, mode){
    var obj = theform || event.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 "limitb" :
          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 ? "20" : "19") + y)|0;}
  }
};

var validation = {
  notnull: function($container, $element, content, errormessage) {
    if (isnull(content)) {
      showerrormessage($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;
  }
};

/**
 * 检查是否为空
 */
var isnull = function(item){
  if(item == null || item == "" || item.replace(/(^\s*)|(\s*$)/g, "") == "" ){
    return true;
  }
  return false;
};

/**
 * 显示提示信息
 */
var showerrormessage = function($container, $element, content){
  $element.popover({
    content: content,
    trigger: 'manual',
    container: $container
  }).popover('show').on({
      'blur': function(){
        $element.popover('destroy');
        $element.parent().removeclass('has-error');
      },
      'keydown': function(){
        $element.popover('destroy');
        $element.parent().removeclass('has-error');
      }
    }).focus().parent().addclass('has-error');
};

希望本文所述对大家学习有所帮助。