爱尚实训哈尔滨校区,Java培训,大数据培训,Python培训,人工智能培训,计算机培训,IT培训,软件培训

在线咨询

当前位置: 首页> 学习园地

学习资料

    爱尚实训-Ajax(四)案例:实现用户名验证-哈尔滨Java培训

    2018-05-04更新

     

    my.js

    function xmlHttpRequest()

    {

    xmlhttp=null;

    if (window.XMLHttpRequest)

      {// code for all new browsers

      xmlhttp=new XMLHttpRequest();

      }

    else if (window.ActiveXObject)

      {// code for IE5 and IE6

      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

      }

          return xmlhttp;

    }

     

    register.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"

        pageEncoding="UTF-8"%>

    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <html>

    <head>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>Insert title here</title>

    <script type="text/javascript" language="javascript" src="js/my.js"></script>

    <script language="javascript">

       window.onload = function(){

      var username =  document.getElementById("username");

      var msg = document.getElementById("msg");

      username.onblur = function(){

      

      //1.创建XMLHttpRequest对象

      var req = xmlHttpRequest();

      

      //2.处理响应结果 设置回调函数

      req.onreadystatechange = function(){

      if(req.status == 200 && req.readyState == 4){

      var data = req.responseText;

      alert(data);

      if(data == "ok"){

      msg.innerHTML = "<font color='blue'>用户名可以使用</font>";

      }else{

      msg.innerHTML = "<font color='red'>用户名已被占用</font>";

      }

      }

      };

      //3.建立连接

    req.open("get","<%=pageContext.getServletContext().getContextPath()%>/CheckUserName?username="+username.value);

      //4.发送请求

      req.send(null);

    };

       

    };

    </script>

    </head>

    <body>

    <input type="text" name="username" id="username" /><span id="msg"></span><br />

    <input type="password" name="userpwd" id="userpwd" />

    </body>

    </html>

     

    servlet

    response.setContentType("text/html;charset=UTF-8");

    request.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    String username = request.getParameter("username");

    if("admin".equals(username)){

    out.print("ok");

    }