当前位置 博文首页 > ajax实现用户名校验的传统和jquery的$.post方式(实例讲解)

    ajax实现用户名校验的传统和jquery的$.post方式(实例讲解)

    作者:姜飞祥 时间:2021-09-21 19:14

    第一种:传统的ajax异步请求,后台代码以及效果在最下边

    首先我们在eclipse中创建一个注册页面regist.jsp,创建一个form表单,注意,由于我们只是实现用户名校验的效果,下边红色部门是我们需要研究对象,所以其他的部门可以忽略不看。

    内容如下:

    <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>用户注册</title>
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/css/login.css" rel="external nofollow" >
    <script type="text/javascript">
    //第三步:ajax异步请求用户名是否存在
     function checkUsername(){
    // 获得文本框值:
    var username = document.getElementById("username").value;
    // 1.创建异步交互对象
    var xhr = createXmlHttp();//第二步中已经创建xmlHttpRequest,这里直接调用函数就可以了。
    // 2.设置监听
    xhr.onreadystatechange = function(){
    if(xhr.readyState == 4){
    if(xhr.status == 200){
    
    //把返回的数据放入到span中
    document.getElementById("span").innerHTML = xhr.responseText;//responseText是后台返回的数据
    }
    }
    }
    // 3.打开连接
    xhr.open("GET","${pageContext.request.contextPath}/user_findByName.action?time="+new Date().getTime()+"&username="+username,true);
    // 4.发送
    xhr.send(null);
    } 
    
    
    //第二部:创建xmlHttp对象
    function createXmlHttp(){
    var xmlHttpRequest;
    try{ // Firefox, Opera 8.0+, Safari
    xmlHttp=new XMLHttpRequest();
    }
    catch (e){
    try{// Internet Explorer
    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e){
    try{
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e){}
    }
    }
    return xmlHttpRequest;
    } 
    function change(){
    var img1 = document.getElementById("checkImg");
    img1.src="${pageContext.request.contextPath}/checkImg.action?"+new Date().getTime();
    }
    </script>
    </head>
    <body>
    <form action="${pageContext.request.contextPath }/user_regist.action" method="post" onsubmit="return checkForm()";>
    <div class="regist">
    <div class="regist_center">
    <div class="regist_top">
    <div class="left fl">会员注册</div>
    <div class="right fr"><a href="${pageContext.request.contextPath }/index.jsp" rel="external nofollow" target="_self">小米商城</a></div>
    <div class="clear"></div>
    <div class="xian center"></div>
    </div>
    <div class="regist_main center">
    
    //第一步:首先,我们创建一个用户名input输入框,并添加一个onblur="checkUsername()"事件
    <div class="username">用&nbsp;&nbsp;户&nbsp;&nbsp;名:&nbsp;&nbsp;<input class="shurukuang" type="text"  name="username" onblur="checkUsername()"/><span ></span></div>
    <div class="username">密&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;码:&nbsp;&nbsp;<input class="shurukuang" type="password"  name="password"/></div>	
    <div class="username">确认&nbsp;密码:&nbsp;<input class="shurukuang" type="password"  name="repassword" /></div>
    <div class="username">邮&nbsp;&nbsp;箱&nbsp;&nbsp;号:&nbsp;&nbsp;<input class="shurukuang" type="email"  name="email" /></div>
    <div class="username">姓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;名:&nbsp;&nbsp;<input class="shurukuang" type="text"  name="name"/></div>
    <div class="username">手&nbsp;&nbsp;机&nbsp;&nbsp;号:&nbsp;&nbsp;<input class="shurukuang" type="text"  name="phone"/></div>
    <div class="username">地&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;址:&nbsp;&nbsp;<input class="shurukuang" type="text"  name="addr"/></div>
    <div class="username">
    <div class="left fl">验&nbsp;&nbsp;证&nbsp;&nbsp;码:&nbsp;&nbsp;<input class="yanzhengma" type="text"  name="checkcode" maxlength="4"/></div>
    <div class="right fl"><img  class="captchaImage" src="${pageContext.request.contextPath}/checkImg.action" onclick="change()" title="点击更换验证码"></div>
    <div class="clear"></div>
    </div>
    </div>
    <div class="regist_submit">
    <input class="submit" type="submit" name="submit" value="立即注册" >
    </div>	
    </div>
    </div>
    </form>
    </body>
    </html>

    第二种方式:使用jQuery中的ajax实现以上效果。首先form表单以及Action中的都不变,我们只需改变script就可以了。

    第一步:引入js文件<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-3.2.1.min.js"></script>

    第二步:

    //ajax异步请求用户名是否存在
    $(function(){
    $('#username').change(function(){//给username添加一个change事件
    var val = $(this).val();//获取输入框的值
    val = $.trim(val);//去空
    if(val != ""){//判断值是否为空
    var url = "${pageContext.request.contextPath}/user_findByName.action";//url还是那个URL
    var args ={"time":new Date().getTime(),"username":val};//这里和上面不同的是,这里用json方式实现传入的time和username参数
    $.post(url,args,function(data){//发送post请求,后台返回的数据在data里面,
    $('#span').html(data);//把后台返回的数据放入span中
    });
    }	
    });
    })

    然后我们来看一下后台数据上会怎么返回的。由于我这是使用ssh框架实现的,为了方便,所以我只展示在Action中是怎么返回数据的,关于ssh框架中service层,dao层的实现请自行解决。

    public class UserAction extends ActionSupport implements ModelDriven<User> {
    private static final long serialVersionUID = 1L;
    /**
    * 模型驱动
    */
    private User user = new User();
    
     
    
    @Override
    public User getModel() {
    
     
    
    return user;
    }
    
    // 注入UserService
    private UserService userService;
    
    public void setUserService(UserService userService) {
    this.userService = userService;
    }
    
    /**
    * AJAX进行异步校验用户名的执行方法
    * 
    * @throws IOException
    */
    public String findByName() throws IOException {
    User existUser = userService.findByName(user.getUsername());//调用service层的方法返回数据库中查询出来的对象
    // 获得response对象,向页面输出:
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setContentType("text/html;charset=UTF-8");//设置编码格式
    // 判断返回的对象是否为空
    if (existUser != null) {
    // 如果有,查询到该用户:用户名已经存在
    response.getWriter().println("用户名已经存在");
    } else {
    // 如果没有,用户名可以使用
    response.getWriter().println("<font color='green'>用户名可以使用</font>");
    }
    return NONE;//此处返回空
    }

    效果如下:

    以上这篇ajax实现用户名校验的传统和jquery的$.post方式(实例讲解)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持站长博客。

    jsjbwy
    下一篇:没有了