Lecture 3: Using ajax technology to implement asynchronous login function (XMLHttpRequest)

Encapsulate the XMLHttpRequest object to realize the ajax asynchronous login function; use three different methods to realize the login function,

Method 1: return the text content;

Method 2: return data in JSON format;

Method 3: Use fastJSON to generate JSON data and return to the front-end page;

project structure

ajax.js file code

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);
    }
}

Method 1 case

login.html source code

<!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 {

    }
}

running result

Method two case

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();
    }

running result

Method three case

Use fastjson:
* 1. To download the jar package of fastjson, add it to the lib folder
* 2. Click on the project structure and add the jar package to the dependency

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();


    }

running result

I have been engaged in software project development for more than 20 years. Since 2005, I have been engaged in teaching Java engineer series courses. I have recorded more than 50 high-quality video courses, including java basics, jspweb development, SSH, SSM, SpringBoot, SpringCloud, artificial intelligence, online payment, etc. Commercial projects, each course includes project practice, class PPT, and complete source code download, interested friends can take a look at my online classroom

Lecturer classroom link: https://edu.csdn.net/lecturer/893

 

Guess you like

Origin blog.csdn.net/software7503/article/details/131324059