第9章 基于JQuery的Ajax处理

1. Ajax的工作原理

Ajax 是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。
Ajax可以使用原生JS进行创建使用,但是原生JS的Ajax的浏览器兼容性较差。一般在工作中很少使用原生方式创建Ajax的代码。在商业化项目中通常会使用第三方的JS库中的Ajax功能来实现异步请求。

与传统请求方式的比较

与传统请求方式的比较

Ajax的运行原理
Ajax的运行原理

2. 利用JQuery实现Ajax

数据库

假期类型表

剩余假期天数表

数据库连接工具类略
PO类

public class AskTypePO {
    
    private int atypeid;
    private String atype;
    
    public int getAtypeid() {
        return atypeid;
    }
    public void setAtypeid(int atypeid) {
        this.atypeid = atypeid;
    }
    public String getAtype() {
        return atype;
    }
    public void setAtype(String atype) {
        this.atype = atype;
    }
}

DAO类

public class SystemDAO {
    
    public List<AskTypePO> getAskTypeList(Connection conn) throws Exception {
        String sql = "select atypeid, atype from asktype";
        PreparedStatement pst = null;
        ResultSet rs = null;
        List<AskTypePO> list = new ArrayList<AskTypePO>();
        try {
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while(rs.next()) {
                AskTypePO po = new AskTypePO();
                po.setAtypeid(rs.getInt("atypeid"));
                po.setAtype(rs.getString("atype"));
                list.add(po);
            }
            
        } catch (Exception e) {
            throw e;
        } finally {
            DBUtil.close(pst, rs);
        }
        return list;
    }
    
    public int getRestDaysByEmpidAndTypeid(Connection conn, int empid, int typeid) throws Exception {
        String sql = "select rdays from restdays where empid = ? and atypeid = ?";
        PreparedStatement pst = null;
        ResultSet rs = null;
        int r = -1;
        try {
            pst = conn.prepareStatement(sql);
            pst.setInt(1, empid);
            pst.setInt(2, typeid);
            rs = pst.executeQuery();
            while(rs.next()) {
                r = rs.getInt("rdays");
            }
            
        } catch (Exception e) {
            throw e;
        } finally {
            DBUtil.close(pst, rs);
        }
        return r;
    }
}

Service类

public class SystemService {

    private SystemDAO dao = new SystemDAO();
    
    public List<AskTypePO> getAskTypeList(){
        Connection conn = DBUtil.getConnection();
        List<AskTypePO> list = null;    
        try {
            list = dao.getAskTypeList(conn);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }   
        return list;    
    }
    
    public int getRestDays(int empid, int typeid){
        Connection conn = DBUtil.getConnection();
        int r = -1;
        try {
            r = dao.getRestDaysByEmpidAndTypeid(conn, empid, typeid);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            DBUtil.close(conn);
        }   
        return r;   
    }
}

Servlet类
EntryQingJiaServlet

@WebServlet("/EntryQingJiaServlet")
public class EntryQingJiaServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        //查询数据库,获得所有的请假类型
        SystemService ss = new SystemService();
        List<AskTypePO> list = ss.getAskTypeList();
        //将查询结果放入Request作用域
        request.setAttribute("alist", list);
        request.getRequestDispatcher("/qingjia.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

AjaxGetRestDaysServlet

@WebServlet("/AjaxGetRestDaysServlet")
public class AjaxGetRestDaysServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        
        //得到ajax提交的数据
        String t = request.getParameter("t");
        String a = request.getParameter("a");
        
        System.out.println(t);
        System.out.println(a);
        //根据数据查询数据库获得结果
        SystemService ss = new SystemService();
        int r = ss.getRestDays(2, Integer.parseInt(t));

        //响应客户端(通过out对象输出结果)
        response.setContentType("text/plain");
        PrintWriter out = response.getWriter();
        out.println(r);
        out.flush();
        out.close();
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}

JSP
index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
    <a href="${pageContext.request.contextPath}/EntryQingJiaServlet">申请休假</a>
</body>
</html>

qingjia.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>申请休假</title>
<script src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function (){
        $("#asktype").change(function (){
            var typeid = $(this).val();
            //将typeid发给servlet
            $.ajax({
                url: "${pageContext.request.contextPath}/AjaxGetRestDaysServlet",
                data: {"t":typeid,"a":"哈哈"},
                type: "post",
                dataType: "text",
                async : true,
                error : function (XMLHttpRequest, textStatus, errorThrown){
                    alert("Ajax出错")
                },
                success : function (data){
                    if(data == -1){
                        data = "无限制";
                    }
                    $("#days").html(data);
                }
            });
        });
    });
</script>
</head>
<body>
    休假类型:
    <select id="asktype">
        <option value="-1">=请选择=</option>
        <c:forEach var="a" items="${alist}">
            <option value="${a.atypeid}">${a.atype}</option>
        </c:forEach>
    </select>
    <br>
    可用天数:<span id="days">无限制</span>
</body>
</html>

推荐阅读更多精彩内容