美文网首页
ajax例子:检查用户是否已经存在

ajax例子:检查用户是否已经存在

作者: Xeon_CC | 来源:发表于2019-06-16 20:00 被阅读0次

ajax原理详解,通俗易懂!!!想学的同学一定要看此文章啊
http://www.sohu.com/a/238246281_100109711

1、目录结构

创建WebProjec, javaEE version为6.0


image.png

2、Servlet: CheckUsernameAction (相当于服务端)

package com.bjpowernode.ajax.web.action;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CheckUsernameAction extends HttpServlet {

    public CheckUsernameAction() {
        super();
    }

    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out=response.getWriter();
        //获取用户名
        String username=request.getParameter("username");
        //链接数据库验证用户名是否存在
        
        HttpSession se=request.getSession();
        
        if(username!=null){
            if("admin".equals(username)){
                //用户名不可用
                out.println("<font color='red'>用户名已被注册</font>");
            }else{
                //用户名可用
                out.println("<font color='green'>用户名可用</font>");
            }
        }
        String password=request.getParameter("password");
        if(password!=null){
        if("123456".equals(password)){
            out.println("<font color='green'>密码正确</font>");
        }else{
            out.println("<font color='red'>密码错误</font>");
        }
        //响应信息给浏览器
        }
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        doGet(request, response);
    }

    public void init() throws ServletException {
        // Put your code here
    }

}




3、index.jsp (相当于客户端,包含源代码详解)

ajax代码写法分为4个步骤:
1,创建ajax核心对象XMLHttpRequest(浏览器内置的,可以直接使用)
2,注册回调函数
3,开启浏览器和服务器之间的通道,此时,xhr.readyState==1
4,发送ajax请求
双横线之间的代码是ajax的主要部分,其他是我自己加的

<%@page contentType="text/html; charset=UTF-8"%>
<!doctype htlm>
<html>
    <head>
    <title>使用ajax发送get请求验证用户名时候可用</title>   
<%--    <base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" /> --%>
    </head>
    
    <body>
        <script type="text/javascript">
        //========================================================================================================
        function checkUsername(uname){
        var xhr;
        //发送ajax请求的代码包括四步,这是四个步骤是固定的
        //ajax发送请求全靠浏览器内置的这个对象,XMLHttpRequest对象
        //使用这个XMLHttpRequest对象可以在浏览器当中单独启动一个新的浏览器线程,通过浏览器线程发送该请求,达到异步效果
//      1,创建ajax核心对象XMLHttpRequest(浏览器内置的,可以直接使用)
        if(window.XMLHttpRequest){
            xhr=new XMLHttpRequest();
        }else{
            //不支持XMLHttpRequest对象,IE5,IE6是不支持的,它只支持ActiveXObject对象
            //IE5,IE6版本使用的是ActiveXObject这两个内置对象发送ajax请求
            xhr=new ActiveXObject("Microsoft.XMLHTTP");
        }
//          alert(xhr);

//      2,注册回调函数
        //程序执行到这里的时候,后面的回调函数并不会执行,只是将回调函数注册给xhr对象
        //等xhr对象的readyState发生改变的时候,后面的回调函数会执行
        /*
            XMLHttpRequest对象在请求和响应的过程中,该对象的readyState状态从0--4
            0: 请求未初始化           xhr.readyState==0
            1: 服务器连接已建立             xhr.readyState==1
            2: 请求已接收                xhr.readyState==2
            3: 请求处理中                xhr.readyState==3
            4: 请求已完成,且响应已就绪 xhr.readyState==4
        */
        //xhr.readyState的值每变一次调用一次
        xhr.onreadystatechange=function(){
//          alert(xhr.readyState);
            if(xhr.readyState==4){  //服务器响应结束
                if(xhr.status==200){
                    //在浏览器端使用xhr对象接受服务器端响应回来的文本
                    var s=xhr.responseText;
                    document.getElementById("nameTipMsg").innerHTML=s;
                }else{
                    //弹出错误代码。xhr.status属性可以获取到HTTP的响应状态码
                    alert(xhr.status);
                }
                
            }
            
        }
        
//      3,开启浏览器和服务器之间的通道,此时,xhr.readyState==1
        //method:指定请求方式为get还是post       url:请求路劲        async:true||false(true表示异步,false表示支持同步) 
        //xhr.open(method,url,asyn);
        xhr.open("get","servlet/CheckUsernameAction?username="+uname,true); //这里只开启通道,不发送请求
        
//      4,发送ajax请求
        xhr.send(); //这里才会发送请求
            
        }
        
                //给按钮对象注册一个鼠标单击事件,当按钮上发生鼠标单击的时候,执行回调函数
        /* myBtn.onclick=function(){
            
        } */
//============================================================================================================

        function checkPwdname(pwd){
        var xhr;
            if(window.XMLHttpRequest){
                xhr=new XMLHttpRequest();
            }else{
                xhr=new ActiveXObject("Microsoft.XMLHTTP");
            }
            
            xhr.onreadystatechange=function(){
            if(xhr.readyState==4){  //服务器响应结束
                if(xhr.status==200){
                    var s=xhr.responseText;
                    document.getElementById("pwdTipMsg").innerHTML=s;
                }else{
                    alert(xhr.status);
                }
                
            }
            
        }
        
            xhr.open("get","servlet/CheckUsernameAction?password="+pwd,true);
            xhr.send(); 
        }


        function aa(){
            if((document.getElementById("uname").value=="abc")&&(document.getElementById("upwd").value=="123456")){
                document.getElementById("sub").setAttribute("type", "submit");
                document.getElementById("form").setAttribute("action", "/ajax/servlet/CheckUsernameAction");
            }else{
                document.getElementById("sub").setAttribute("type", "button");
                document.getElementById("form").setAttribute("action", "");
            }
        }

        </script>
        
        <form method='post' id="form">
        用户名:<input type="text" id="uname" name="username" onblur="checkUsername(this.value)"><span id="nameTipMsg"></span><br>
        密码:<input type="password" id="upwd" name="password" onblur="checkPwdname(this.value)"><span id="pwdTipMsg"></span><br><br>
        <input onclick='aa()' type='button' value='SUBMIT' id="sub">
        </form>
    </body>
</html>

4、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
    <display-name>ajax</display-name>
  <servlet>
    <servlet-name>CheckUsernameAction</servlet-name>
    <display-name>This is the display name of my J2EE component</display-name>
    <description>This is the description of my J2EE component</description>
    <servlet-class>com.bjpowernode.ajax.web.action.CheckUsernameAction</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>CheckUsernameAction</servlet-name>
    <url-pattern>/servlet/CheckUsernameAction</url-pattern>
  </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>



5、测试:

右边的文字是服务端Servlet里面的内容,在一个客户端页面中,既包含用户的内容又包含服务器响应获得的内容,服务端响应得到内容达到局部刷新的效果


image.png

用户名为abc,密码为123456


image.png
单击提交按钮后转到服务器界面
image.png

用户名密码为其他的话是不能通过按钮跳转到服务器页面的

相关文章

网友评论

      本文标题:ajax例子:检查用户是否已经存在

      本文链接:https://www.haomeiwen.com/subject/bbtnfctx.html