Ajax有关小案例(一)

一、判断用户名是否存在

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
	<%--1、导入JQuery库--%>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
            // 2、获取name=“username”的节点:username
            // 3、为username添加change响应函数
            $(":input[name='username']").change(function () {
                // 3.1、获取username的value属性,去除前后格即不为空,准备发送Ajax请求
                var val=$(this).val();
                val=$.trim(val);
                // 3.2、发送Ajax请求,检验username是否可用
                if (val!="") {
                    var url="${pageContext.request.contextPath}/valiateUserName";
                    var args={"userName": val,"time":new Date()};
                    // 3.3、在服务端直接返回一个html的片段
                    // 3.4、在客户端浏览器把其添加到#message中
                    $.post(url,args,function (data) {
                        $("#message").html(data);
                    })
                }
            })
        })
    </script>
  </head>
  <body>
    <form action="" method="post">
      UserName: <input type="text" name="username">
       <br>
        <div id="message"></div>
       <br>
      <input type="submit" value="Submit">
        <br>
    </form>
  </body>
</html>
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.util.Arrays;
import java.util.List;

@WebServlet(name ="valiateUserNameServlet",urlPatterns = "/valiateUserName",asyncSupported = true)
public class valiateUserNameServlet extends HttpServlet {
    private static final long serialVersionUID=1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<String> userNames= Arrays.asList("AAA","BBB","CCC");
        String userName=req.getParameter("userName");
        String result=null;
        if (userNames.contains(userName)) {
            result="<font color='red'>该用户名已经被使用</font>";
        } else {
            result="<font color='green'>该用户名可以被使用</font>";
        }
        resp.setContentType("text/html;charset=utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(result);
    }
}

二、加入购物车(jackson)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <%--1、导入JQuery库--%>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-3.5.1.min.js"></script>
    <script type="text/javascript">
        $(function () {
             // 判断是否有购物车
             // 如果没有,则隐藏购物车;如果有,则显示购物车及其数据
            var isHasCar="${sessionScope.sc==null}";
            if (isHasCar=="true") {
                $("#carstatus").hide();
            } else {
                $("#carstatus").show();

                $("#bookName").text("${sessionScope.sc.bookName}");
                $("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}");
                $("#totalMoney").text("${sessionScope.sc.totalMoney}");
            }

            // 1、获取当前页面所有a节点,并为每一个a节点都添加onclick响应函数,同时取消其默认行为
            $("a").click(function () {
                $("#carstatus").show();
                // 2、准备发送Ajax请求:url(a的节点的href属性);args(时间戳)
                var url=this.href;
                var args={"time": new Date()};
                // 3、响应为一个json对象,包括:bookName,totalBookNumber,totalMoney
                $.getJSON(url,args,function (data) {
                    // 4、把对应的属性添加到对应的位置
                    $("#bookName").text(data.bookName);
                    $("#totalBookNumber").text(data.totalBookNumber);
                    $("#totalMoney").text(data.totalMoney);
                });
                return false;
            });
        })
    </script>
  </head>
  <body>
    <div id="carstatus">
        <%--    您已将xxx加入购物车,购物车中的书有xx本,总价格xxx钱。--%>
        您已将&emsp; <span id="bookName"></span>&emsp;加入到购物车中,
        购物车中的书有&emsp; <span id="totalBookNumber"></span>&emsp;本,
        总价格&emsp; <span id="totalMoney"></span>&emsp;钱。
    </div>
    <br>
    Java&emsp;<a href="${pageContext.request.contextPath}/addToCar?id=Java&price=100">加入购物车</a>
    <br><br>
    Oracle&emsp;<a href="${pageContext.request.contextPath}/addToCar?id=Oracle&price=200">加入购物车</a>
    <br><br>
    Structs2&emsp;<a href="${pageContext.request.contextPath}/addToCar?id=Structs2&price=300">加入购物车</a>
    <br><br>
  </body>
</html>
package com.join.beans;

import java.util.HashMap;
import java.util.Map;

// 加入购物车后,书名,书数量,书总价钱的变化

public class ShoppingCar {
//    存放ShoppingCarItem的Map: 键:书名,值:ShoppingCarTtem对象
    private Map<String, ShoppingCarItem> items=new HashMap<String, ShoppingCarItem>();
    private String bookName;

    public void addToCart(String bookName,int price) {
        this.bookName=bookName;
        if (items.containsKey(bookName)) {
            // 如果购物车中原本包含该书籍,则总数量加一
            ShoppingCarItem item=items.get(bookName);
            item.setNumber(item.getNumber()+1);
        } else {
            ShoppingCarItem item=new ShoppingCarItem();
            item.setBookName(bookName);
            item.setPrice(price);
            item.setNumber(1);

            items.put(bookName,item);
        }
    }

    public String getBookName() {
        return bookName;
    }
    public int getTotalBookNumber() {
        int total=0;
        for (ShoppingCarItem item:items.values()) {
            total+=item.getNumber();
        }
        return total;
    }
    public int getTotalMoney(){
        int money=0;
        for (ShoppingCarItem item:items.values()) {
            money+=item.getNumber()*item.getPrice();
        }
        return money;
    }
}
package com.join.beans;

// 商品相关信息

public class ShoppingCarItem {
    private int number;
    private String bookName;
    private int price;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getBookName() {
        return bookName;
    }

    public void setBookName(String bookName) {
        this.bookName = bookName;
    }

    public int getPrice() {
        return price;
    }

    public void setPrice(int price) {
        this.price = price;
    }

}
package com.join.Servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.join.beans.ShoppingCar;

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 javax.servlet.http.HttpSession;
import java.io.IOException;

// 连接jsp及java代码

@WebServlet(name ="addToCarServlet",urlPatterns = "/addToCar",asyncSupported = true)
public class addToCarServlet extends HttpServlet {
    private static final long serialVersionUID=1L;

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

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        1、获取请求的参数
        String bookName=req.getParameter("id");
        int price=Integer.parseInt(req.getParameter("price"));
//        2、获取购物车对象
        HttpSession session=req.getSession();
        ShoppingCar sc=(ShoppingCar) session.getAttribute("sc");
//        判断购物车是否为空
        if (sc==null) {
            sc=new ShoppingCar();
            session.setAttribute("sc",sc);
        }
//        3、把点击的选项加入到购物车中
        sc.addToCart(bookName,price);
//        4、准备响应的JSON对象{"bookName": "";"totalBookNumber": 1,"totalMoney": 1}
        StringBuilder result=new StringBuilder();
//        如果从服务端返回一个JSON字符串,要求必须是双引号,例如{"bookName": ""}
        result.append("{")
                .append("\"bookName\": \""+bookName+"\"")
                .append(",")
                .append("\"totalBookNumber\": \""+sc.getTotalBookNumber()+"\"")
                .append(",")
                .append("\"totalMoney\": \""+sc.getTotalMoney()+"\"")
                .append("}");
//       5、响应JSON对象
        resp.setContentType("text/html");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().print(result);
    }
}
<?xml version="1.0" encoding="UTF-8"?>
<!--相关配置-->
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>addToCarServlet</servlet-name>
        <servlet-class>com.join.Servlet.addToCarServlet</servlet-class>
        <async-supported>true</async-supported>
    </servlet>
    <servlet-mapping>
        <servlet-name>addToCarServlet</servlet-name>
        <url-pattern>/addToCar</url-pattern>
    </servlet-mapping>
</web-app>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值