Javaweb05-Ajax
阅读原文时间:2023年07月11日阅读:3

1.1 基本Ajax

参数

说明

url

请求地址

type

请求类型

data

请求参数

dataType

返回参数

success

成功处理函数

error

错误处理函数

<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
    $(function(){
        //强调:基于javascript实现的ajax用法,比较繁琐,不需要掌握
        //需要掌握的是基于jQuery方式使用的Ajax
        //当用户登录,输入用户名后,失去焦点,校验登录用户名再系统中是否被使用
        $("#uname").blur(function(){
            //alert($(this).val());
            //获取输入的用户名,并实现非空校验
            var userName = $(this).val();
            if(userName == null || userName == ""){
                alert("用户名不能为空");
                return;
            }

            //基于jAuery的Ajax用法-基本用法
            $.ajax({
                "url" : "<%=request.getContextPath()%>/checkUserName",
                "type" : "post",
                "data" : {"userName" : userName},
                "dataType" : "text",
                "success" : function(data){
                    //alert(JSON.parse(data));
                    if(JSON.parse(data)){
                        $("#showMsg").html("用户名存在").css({"color":"red"});
                    }else{
                        $("#showMsg").html("用户名可用").css({"color":"#2ceb0a"});
                    }
                },
                "error" : function(){
                    $("#showMsg").html("未知错误");
                }
            });
</script>

1.2 get提交Ajax

语法:$.get(url,params,success);

//基于JQuery的Ajax用法-扩展用法1,简写Get方,Ajax请求
//语法:$.get(url,params,success)
$.get("<%=request.getContextPath()%>/checkUserName",{"userName":serName},function(data){
    if(JSON.parse(data)){
        $("#showMsg").html("用户名存在get").css({"color":"red"});
    }else{
        $("#showMsg").html("用户名可用get").css({"color":"#2ceb0a"});
    }
});

1.3 post提交Ajax

语法:$.post(url,params,success);

//基于JQuery的Ajax用法-扩展用法1,简写Get方,Ajax请求
//语法:$.post(url,params,success)
$.post("<%=request.getContextPath()%>/checkUserName",{"userName" : userName},function(data){
    if(JSON.parse(data)){
        $("#showMsg").html("用户名存在post").css({"color":"red"});
    }else{
        $("#showMsg").html("用户名可用post").css({"color":"#2ceb0a"});
    }
});

1.4 请求处理

checkUserName 对应的处理代码;通过Response返回结果,前端接收到结果并进行处理;

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //后台接收用户名,校验是否重复
    //获取用户参数
    String userName = req.getParameter("userName");
    System.out.println("AjaxServlet userName=>>"+userName);

    //定义返回的结果
    boolean result= false;

    //模拟调用业务,查询当前用户名再数据中是否有记录
    List<String> userNames = Arrays.asList("kh96","kgc","Ajax");
    if(userNames.contains(userName)) {
        result = true;
    }

    //异步请求响应结果,注意println不可以用,返回的结果会带\n
    System.out.println("AjaxServlet result==>"+result);
    resp.getWriter().println(result);
}

2.1 登录页面

loginAnime.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<title>登录页面</title>
<style type="text/css">
    table{
        background-color:pink;
    }
</style>
</head>
<body>
    <form action="<%=request.getContextPath()%>/loginAnime" method="get">
        <table border="1px" align="center" width="40%" cellspacing="0">
            <tr style="hight:60px; font-size:16px;background-color:#B9DEE0">
                <th colspan="2"> 欢迎登录课工场KH96动漫管理系统 </th>
            </tr>
            <tr>
                <td>用户名:</td>
                <td>
                    <input type="text" name="uname" id="uname" placeholder="请输入"用户名> </input>
                    <span id = "showMsg"   style="text-align:center;"></span>
                </td>
            </tr>
            <tr>
                <td>用户密码:</td>
                <td>
                    <input type="password" name="upwd" id="upwd" placeholder="请输入用户密码"> </input>
                </td>
            </tr>
            <tr>
                <td colspan="2" align="center">
                    <input type="submit" value="立即登录" />
                    <input type="reset" value="重新填写" />
                </td>
            </tr>
        </table>
    </form>
</body>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.4.1.min.js" ></script>
<script type="text/javascript">
    $(function(){
        $("#uname").blur(function(){
            //异步请求校验用户名
            //基于jAuery的Ajax用法-基本用法
            $.post("<%=request.getContextPath()%>/checkUserName",{"userName" :$("#uname").val()},function(data){
                if(JSON.parse(data)){
                    $("#showMsg").html("用户名存在").css({"color":"#2ceb0a"});
                }else{
                    $("#showMsg").html("用户名不存在").css({"color":"red"});
                }
            });
        });

        $("form").submit(function(){
            //用户名非空校验
            var userName = $("#uname").val();
            //alert(userName);
            if(userName == null || userName == ""){
                alter("用户名不能为空");
                //submi事件,接收false结果,会自动取消表单的提交
                return false;
            }

            //密码非空
            var userPwd = $("#upwd").val();
            //alert(userPwd);
            if(userPwd == null || userPwd == ""){
                alter("用户密码不能为空");
                //submi事件,接收false结果,会自动取消表单的提交
                return false;
            }

            //异步提交登录请求,如果交谈用户信息输入正确,提示登录成功,宁跳转到动漫管理首页,否则提示登录失败
            $.post("<%=request.getContextPath()%>/loginAnime",{"userName" : userName,"userPwd":userPwd},function(data){
                if(JSON.parse(data)){
                    alert("登录成功");
                    //请求后台获取动漫列表数据
                    //location.href = "<%=request.getContextPath()%>/animes";
                    //请求列表页面,使用Ajax解析json数据
                    location.href = "animeListJson.jsp";

                }else{
                    alert("登录失败");
                }
            });

            //由于使用了Ajax进行了异步登录请求,此处表单就不能再提交,否者表达再提交会出错
            return false;
        }); 

    });
</script>
</html>

注意:再使用Ajaz提交表单时,一定要返回false,要不然表单会再提交一次;

2.2 存放数据

2.2.1 通过request域转递数据

AnimeServlet

public class AnimeServlet extends HttpServlet {

    private static final long serialVersionUID = -4726403189879316484L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 模拟从数据库获取动漫列表
        List<Animes> animes = new ArrayList<>();
        animes.add(new Animes(961, "玄幻", "斗破苍穹", "土豆", "萧炎", "玄机科技", "2019-08-04"));
        animes.add(new Animes(962, "玄幻", "完美世界", "辰东", "石昊", "福煦影视", "2020-08-05"));
        animes.add(new Animes(963, "言情", "狐妖小红娘", "小新", "白月初", "腾讯动漫", "2021-08-06"));
        animes.add(new Animes(964, "言情", "秦时明月", "温世仁", "天明", "玄机科技", "2022-08-04"));
        animes.add(new Animes(965, "热血", "镇魂街", "许辰", "曹焱兵", "卢李工作室", "2018-08-04"));
        animes.add(new Animes(966, "热血", "雾山五行", "林魂", "闻人翊悬", "六道无鱼", "2018-08-04"));

        //将动漫集合放入request作用域
        req.setAttribute("animes", animes);

        //转发到动漫列表页面
        req.getRequestDispatcher("web5AjaxAndJquery/animeList.jsp").forward(req, resp);

    }
}

2.2.2 将数据转成json格式响应

public class AnimeJsonServlet extends HttpServlet {

    private static final long serialVersionUID = -4726403189879316484L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // 模拟从数据库获取动漫列表
        List<Animes> animes = new ArrayList<>();
        animes.add(new Animes(961, "玄幻", "斗破苍穹", "土豆", "萧炎", "玄机科技", "2019-08-04"));
        animes.add(new Animes(962, "玄幻", "完美世界", "辰东", "石昊", "福煦影视", "2020-08-05"));
        animes.add(new Animes(963, "言情", "狐妖小红娘", "小新", "白月初", "腾讯动漫", "2021-08-06"));
        animes.add(new Animes(964, "言情", "秦时明月", "温世仁", "天明", "玄机科技", "2022-08-04"));
        animes.add(new Animes(965, "热血", "镇魂街", "许辰", "曹焱兵", "卢李工作室", "2018-08-04"));
        animes.add(new Animes(966, "热血", "雾山五行", "林魂", "闻人翊悬", "六道无鱼", "2018-08-04"));

        //将集合数据,转换为json字符串,返回给前端
        //阿里巴巴的fasejson,将集合转换为json字符串
        String animesJson = JSON.toJSONString(animes);

        System.out.println(animesJson);

        //响应
        resp.setContentType("text/html;charset=UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().print(animesJson);

    }
}

3、获取并展示数据

3.1 通过EL表达式取出request域域中的数据

animeList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!-- 核心标签库 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!-- 格式化标签库 -->
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!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>动漫主页</title>
    </head>
    <body>
        <h2 style="text-align: center">课工场KH96班动漫管理系统</h2>
        <p style="text-align: center">
            名称:<input type="text" name="animeName" size="15"/>
            作者:<input type="text" name="animeAuthor" size="15"/>
            分类:<select name="animeCategory">
                <option value="0">全部</option>
                <option value="1">玄幻</option>
                <option value="2">武侠</option>
                <option value="3">言情</option>
                <option value="4">机甲</option>
            </select>
            <input type="button" value = "搜索"/>
        </p>
        <table border="1px" width="90%" cellspacing="0" align="center">
            <thead>
                <tr style="height: 80px; font-size: 30px; background-color: cyan;">
                    <th colspan="8">动漫详情列表</th>
                </tr>
                <tr>
                    <th colspan="8" style="text-align: right;">欢迎:&nbsp;&nbsp;<a href="logout">退出登录</a></th>
                </tr>
                <tr style="height: 40px; background-color: cyan;">
                    <th>编号</th>
                    <th>分类</th>
                    <th>名称</th>
                    <th>作者</th>
                    <th>主角</th>
                    <th>出品</th>
                    <th>时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <!-- tbody中是动态加载的数据列表 -->
                <c:forEach items="${animes}" var ="anime" varStatus="status">
                    <tr align="center"
                        <c:if test="${status.index % 2 == 1 }">
                            style = "background-color: pink;"
                        </c:if>
                    >
                        <td>${anime.animeId }</td>
                        <td>${anime.animeCategory } </td>
                        <td>${anime.animeNaem } </td>
                        <td>${anime.animeAuthor } </td>
                        <td>${anime.animeActor } </td>
                        <td>${anime.animeProduce } </td>
                        <td>${anime.animeTime } </td>
                        <td>
                            <a href="#">修改</a> &nbsp;&nbsp; | &nbsp;&nbsp;
                            <a href="#">删除</a>
                        </td>
                    </tr>
                </c:forEach>
            </tbody>
            <tfoot>
                <tr>
                    <td colspan="8" style="height: 40px; text-align: center">
                        <input type="button" value="添加" id="addAnime"/>&nbsp;&nbsp;
                        <a href="#">首页</a>&nbsp;|&nbsp;
                        <a href="#">&lt;&lt;上一页</a>&nbsp;|&nbsp;
                        <a href="#">下一页&gt;&gt;</a>&nbsp;|&nbsp;
                        <a href="#">尾页</a>&nbsp;|&nbsp;
                        共&nbsp;6&nbsp;条&nbsp;&nbsp;每页&nbsp;10&nbsp;条&nbsp;当前第&nbsp;1&nbsp;页&nbsp;/&nbsp;共&nbsp;1&nbsp;页
                    </td>
                </tr>
            </tfoot>
        </table>
    </body>

</html>

3.2 直接通过jQuery添加子标签

animeListJson.jsp

//tbody部分
<tbody>
    <!-- 直接通过jQuery添加子标签 -->

</tbody>

//处理成功返回的数据部分
"success": function(data){
    //确定数据动态显示的位置
    var $tbody = $("tbody");
    //alert(data);
    //数据解析

    // 隔行变色
    var count = 1;

    // 数据解析
    $(data).each(function(){
        // 定义颜色
        var bgColor = count % 2 == 0 ? "style='background-color:#ddd;'" : "";
        $("tbody").append(
            "<tr align='center' " + bgColor + ">"
            + "<td>" + this.animeId + "</td>"
            + "<td>" + this.animeCategory + "</td>"
            + "<td>" + this.animeName + "</td>"
            + "<td>" + this.animeAuthor + "</td>"
            + "<td>" + this.animeActor + "</td>"
            + "<td>" + this.animeProduce + "</td>"
            + "<td>" + this.animeTime + "</td>"
            + "<td><a href='#'>修改</a>&nbsp;&nbsp;<a href='#'>删除</a></td>"
            + "</tr>"
        );
        count++;
    });
}

展示效果: