第3讲:使用ajax技术实现异步登录功能(XMLHttpRequest)

封装XMLHttpRequest对象,实现ajax异步登录功能;用三种不同的方法实现登录功能,

方法一:返回文本内容;

方法二:返回JSON格式数据;

方法三:使用fastJSON生成JSON数据,返回前端页面;

项目结构

ajax.js文件代码

var xmlhttp=null;
//创建XMLHttpRequest对象
function createHttpRequest(){
    if(window.XMLHttpRequest){ //Mozilla 浏览器
        xmlhttp = new XMLHttpRequest();
    }else if(window.ActiveXObject){
        try{
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); //新版IE
        }catch(e){
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }catch(e){
                xmlhttp = null;
            }
        }
    }
    if(!xmlhttp){ //创建XMLHttpRequest失败
        alert("不能创建XMLHttpRequest对象实例");
    }
}
//发送函数
function sendRequest(method,url,param,callbackHandler){
    //创建对象
    createHttpRequest();
    //绑定事件,后台返回的数据,通过callback方法处理
    xmlhttp.onreadystatechange = callbackHandler;

    if(method=="get" || method=="GET"){
        //初始化发送信息
        xmlhttp.open(method,url + "?" + param,true);
        xmlhttp.send(null);
    }

    if(method=="post" || method=="POST"){
        //初始化发送信息
        xmlhttp.open(method,url,true);
        xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlhttp.send(param);
    }
}

方法1案例

login.html源码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统登录</title>
    <script src="../js/ajax.js"></script>
    <script type="text/javascript">


        function dataDeal(){
            if(xmlhttp.readyState == 4){
                if(xmlhttp.status == 200) {
                    document.getElementById("errMsg").innerText = xmlhttp.responseText;
                }else {
                    alert(xmlhttp.status);
                }
            }
        }


        function login(){

            var loginName = document.getElementById("loginName").value;
            var pass = document.getElementById("pass").value;
            if(loginName==""){
                document.getElementById("loginNameTip").innerText="请输入用户名称";
                document.getElementById("passTip").innerText="";
                return ;
            }
            if(pass==""){
                document.getElementById("loginNameTip").innerText="";
                document.getElementById("passTip").innerText="请输入登录密码";
                return ;
            }
            var url = "http://localhost:8080/ajaxProj/loginServlet";
            var params = "loginName=" + loginName + "&pass=" + pass;
            sendRequest("post",url,params,dataDeal);

        }

    </script>
</head>
<body>
    <h2 align="center">系统登录</h2>
    <hr>
    <table border="1" align="center" width="800">
        <caption><font id="errMsg" color="red" size="2"></font></caption>
        <tr>
            <td align="right">用户名称:</td>
            <td><input type="text" name="loginName" id="loginName"> </td>
            <td width="200"><font color="red" size="2" id="loginNameTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="right">登录密码:</td>
            <td><input type="password" name="pass" id="pass"> </td>
            <td width="200"><font color="red" size="2" id="passTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="center" colspan="3">
                <input type="button" value="登录" onclick="login();">
            </td>
        </tr>
    </table>

</body>
</html>

LoginServlet.java

package com.servlet;

import com.alibaba.fastjson.JSONObject;
import com.bean.LoginBean;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(name = "LoginServlet",value = "/loginServlet")

public class LoginServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String loginName = request.getParameter("loginName");
        String pass = request.getParameter("pass");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        if(loginName.equals("admin") && pass.equals("1234")){
            //登录成功
            out.write("登录成功");
        }else{
            //登录失败
            out.println("登录失败");
        }
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

运行效果

方法二案例

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统登录</title>
    <script src="../js/ajax.js"></script>
    <script type="text/javascript">


        function dataDeal(){
            if(xmlhttp.readyState == 4){
                if(xmlhttp.status == 200) {
                    document.getElementById("errMsg").innerText = xmlhttp.responseText;
                    //JSON.parse方法的作用:把json格式的文本内容转换为JSON对象
                    var obj = JSON.parse(xmlhttp.responseText);

                    if(obj.code==0){
                        alert(obj.msg);
                        //跳转到其他页面
                        //location.href = "/ajaxProj/T2/menu.html"
                    }else{
                        alert(obj.msg);
                    }
                }else {
                    alert(xmlhttp.status);
                }
            }
        }


        function login(){

            var loginName = document.getElementById("loginName").value;
            var pass = document.getElementById("pass").value;
            if(loginName==""){
                document.getElementById("loginNameTip").innerText="请输入用户名称";
                document.getElementById("passTip").innerText="";
                return ;
            }
            if(pass==""){
                document.getElementById("loginNameTip").innerText="";
                document.getElementById("passTip").innerText="请输入登录密码";
                return ;
            }
            var url = "http://localhost:8080/ajaxProj/loginServlet";
            var params = "loginName=" + loginName + "&pass=" + pass;
            sendRequest("post",url,params,dataDeal);

        }

    </script>
</head>
<body>
    <h2 align="center">系统登录</h2>
    <hr>
    <table border="1" align="center" width="800">
        <caption><font id="errMsg" color="red" size="2"></font></caption>
        <tr>
            <td align="right">用户名称:</td>
            <td><input type="text" name="loginName" id="loginName"> </td>
            <td width="200"><font color="red" size="2" id="loginNameTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="right">登录密码:</td>
            <td><input type="password" name="pass" id="pass"> </td>
            <td width="200"><font color="red" size="2" id="passTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="center" colspan="3">
                <input type="button" value="登录" onclick="login();">
            </td>
        </tr>
    </table>

</body>
</html>

LoginServlet.java

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String loginName = request.getParameter("loginName");
        String pass = request.getParameter("pass");
        response.setContentType("text/json");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        if(loginName.equals("admin") && pass.equals("1234")){
            //登录成功
            //out.write("登录成功");
            //json格式的数据就是键值对
            String msg = "{\"code\":\"0\",\"msg\":\"登录成功\"}";
            out.write(msg);
        }else{
            //登录失败
            String msg = "{\"code\":\"1\",\"msg\":\"登录失败\"}";
            out.println(msg);
        }
        out.close();
    }

运行效果

方法三案例

使用fastjson:
*   1.要下载fastjson的jar包,加入到lib文件夹
*   2.点击项目结构,把jar包加入到依赖里面

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>系统登录</title>
    <script src="../js/ajax.js"></script>
    <script type="text/javascript">


        function dataDeal(){
            if(xmlhttp.readyState == 4){
                if(xmlhttp.status == 200) {
                    document.getElementById("errMsg").innerText = xmlhttp.responseText;
                    //JSON.parse方法的作用:把json格式的文本内容转换为JSON对象
                    var obj = JSON.parse(xmlhttp.responseText);

                    if(obj.loginBean.code==0){
                        alert(obj.loginBean.msg);
                        //跳转到其他页面
                        //location.href = "/ajaxProj/T2/menu.html"
                    }else{
                        alert(obj.loginBean.msg);
                    }
                }else {
                    alert(xmlhttp.status);
                }
            }
        }


        function login(){

            var loginName = document.getElementById("loginName").value;
            var pass = document.getElementById("pass").value;
            if(loginName==""){
                document.getElementById("loginNameTip").innerText="请输入用户名称";
                document.getElementById("passTip").innerText="";
                return ;
            }
            if(pass==""){
                document.getElementById("loginNameTip").innerText="";
                document.getElementById("passTip").innerText="请输入登录密码";
                return ;
            }
            var url = "http://localhost:8080/ajaxProj/loginServlet";
            var params = "loginName=" + loginName + "&pass=" + pass;
            sendRequest("post",url,params,dataDeal);

        }

    </script>
</head>
<body>
    <h2 align="center">系统登录</h2>
    <hr>
    <table border="1" align="center" width="800">
        <caption><font id="errMsg" color="red" size="2"></font></caption>
        <tr>
            <td align="right">用户名称:</td>
            <td><input type="text" name="loginName" id="loginName"> </td>
            <td width="200"><font color="red" size="2" id="loginNameTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="right">登录密码:</td>
            <td><input type="password" name="pass" id="pass"> </td>
            <td width="200"><font color="red" size="2" id="passTip"> &nbsp;</font></td>
        </tr>
        <tr>
            <td align="center" colspan="3">
                <input type="button" value="登录" onclick="login();">
            </td>
        </tr>
    </table>

</body>
</html>

LoginServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String loginName = request.getParameter("loginName");
        String pass = request.getParameter("pass");
        //response.setContentType("application/json");
        response.setContentType("text/json");
        //response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        LoginBean loginBean = new LoginBean();
        loginBean.setCode(0);
        loginBean.setMsg("登录成功");
        //用fastjson转换JSON格式数据
        JSONObject json  = new JSONObject();
        if(loginName.equals("admin") && pass.equals("1234")){
            //登录成功
            json.put("loginBean",loginBean);
            String msg = json.toJSONString();
            out.write(msg);
        }else{
            //登录失败
            loginBean.setCode(1);
            loginBean.setMsg("用户名或密码错误");

            json.put("loginBean",loginBean);
            //把对象转换为JSON格式的字符串
            String msg = json.toJSONString();
            out.println(msg);
        }
        out.close();


    }

运行效果

本人从事软件项目开发20多年,2005年开始从事Java工程师系列课程的教学工作,录制50多门精品视频课程,包含java基础,jspweb开发,SSH,SSM,SpringBoot,SpringCloud,人工智能,在线支付等众多商业项目,每门课程都包含有项目实战,上课PPT,及完整的源代码下载,有兴趣的朋友可以看看我的在线课堂

讲师课堂链接:https://edu.csdn.net/lecturer/893

猜你喜欢

转载自blog.csdn.net/software7503/article/details/131324059