用Ajax和Javascript实现购物车

前端之家收集整理的这篇文章主要介绍了用Ajax和Javascript实现购物车前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
用Ajax和Javascript实现购物车

用Ajax写了一个简易的购物车(做得比较简单),效果如图:
1、首先在数据库中建立了一个商品表,并加入了数据:


2、搭建好tomcat服务器,进入ProServlet可以看到商品信息表:



3、在商品列表中勾选要加入购物车的商品,点击加入购物车,如果商品添加成功,则会弹出添加成功的提示添加失败则弹出添加失败的提示


4、商品加入购物车成功后,点击跳转到购物车,则跳转到购物车列表


5、在购物车列表中增加商品数量


6、在购物车列表中减少商品数量,如果该商品数量为1就直接将该商品从购物车中删除


7、删除单个商品





8、清空购物车




下面就是实现代码
dao层代码
public class ProductDao {
	private Connection conn = null;
	private PreparedStatement ps = null;
	private ResultSet rs = null;
	/**
	 * 查询所有商品信息
	 * @return
	 */
	public List<Product> getProducts(){
		conn  = DBUtil.getConn();
		String sql = "select * from PProduct ";
		List<Product> products = new ArrayList<Product>();
		try {
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			while(rs.next()){
				Product product = new Product();
				product.setId(rs.getInt("id"));
				product.setName(rs.getString("name"));
				product.setPrice(rs.getDouble("price"));
				product.setProdate(rs.getDate("prodate"));
				product.setEffdate(rs.getDate("effdate"));
				product.setUnit(rs.getString("unit"));
				products.add(product);
			}
		} catch (sqlException e) {
			e.printStackTrace();
		}finally{
			DBUtil.close(rs,ps,conn);
		}
		return products;
	}
	/**
	 * 根据商品编号查找单个商品信息
	 * @param id
	 * @return
	 */
	public Product getProductById(int id){
		Product pro = new Product();
		conn = DBUtil.getConn();
		String sql = "select * from pproduct where id = ? ";
		try{
			ps = conn.prepareStatement(sql);
			ps.setInt(1,id);
			rs = ps.executeQuery();
			if(rs.next()){
				pro.setId(rs.getInt("id"));
				pro.setName(rs.getString("name"));
				pro.setPrice(rs.getDouble("price"));
				pro.setProdate(rs.getDate("prodate"));
				pro.setEffdate(rs.getDate("effdate"));
				pro.setUnit(rs.getString("unit"));
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			DBUtil.close(rs,conn);
		}
		return pro;
	}
}

servlet中的代码
public class ProServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	//创建ProService对象
	private ProService service = new ProService();
	
	public void doGet(HttpServletRequest request,HttpServletResponse response)
			throws ServletException,IOException {
		//在doGet()方法调用doPost()
		doPost(request,response);
	}

	public void doPost(HttpServletRequest request,IOException {
		//设置字符集编码格式
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		PrintWriter out = response.getWriter();
		
		//接收从页面传来的操作类型
		String type = request.getParameter("type");
		
		//定义CartService
		CartService cart = null ;
		//创建session
		HttpSession session = request.getSession();
		//从Session当中取购物车,查看此购物车是否存在
		if(null == session.getAttribute("cart")){
			cart = new CartService();
			cart.init();
		}else{
			cart = (CartService)session.getAttribute("cart");
		}
		//将商品加入购物车
		if("add".equals(type)){
			String  ids = request.getParameter("ids");
			//开始封装商品项
			String [] temp = ids.split(",");
			for(String id : temp){
				//id值即为商品编号,查询出商品
				if(null==id||"".equals(id)){
					continue;
				}else{
					Product product =	service.getProductById(Integer.parseInt(id));
					Items item  = new Items();
					item.setProduct(product);
					item.setNum(1);
					cart.add(item);
				}
			}
			//商品已经加入到购物车,将原有的购物车替换掉
			session.setAttribute("cart",cart);
			//向浏览器返回后台操作
			out.print("ok");
		}
		//显示商品列表
		else if(null==type){
			List<Product> products = service.getProducts();
			request.setAttribute("products",products);
			request.getRequestDispatcher("list.jsp").forward(request,response);
		}
		//删除单个商品
		else if("delete".equals(type)){
			int id = Integer.parseInt(request.getParameter("id"));
			boolean result = cart.removePro(id);
			if(result){
				out.print("ok");
			}
		}
		//清空购物车
		else if("clear".equals(type)){
			boolean result = cart.clear();
//			if(result==true){
//				out.print("\t\t\t\t\t\t\t已清空购物车"+"\t\t");
//			}
			request.getRequestDispatcher("cartlist.jsp").forward(request,response);
		}
		//将购物车中商品数量加1
		else if("addOne".equals(type)){
			int id = Integer.parseInt(request.getParameter("id"));
			Product product =	service.getProductById(id);
			Items item  = new Items();
			item.setProduct(product);
			boolean  result = cart.addOne(item);
			if(result){
				out.print("ok");
			}
		}
		//将购物车中商品数量减1,如果该商品只有一个的话就将该商品从购物车中删除
		else if("subOne".equals(type)){
			int id = Integer.parseInt(request.getParameter("id"));
			Product product =	service.getProductById(id);
			Items item  = new Items();
			item.setProduct(product);
			boolean result = cart.subOne(item);
			if(result){
				out.print("ok");
			}
		}
		out.flush();
		out.close();
	}
}


ProService的代码
public class ProService {
	private ProductDao dao = new ProductDao();
	
	public Product getProductById(int id){
		return dao.getProductById(id);
	}
	
	public List<Product> getProducts(){
		return dao.getProducts();
	}
}


CartService的代码
public class CartService {
	private Map<Integer,Items> map;
	public void init(){
		map = new HashMap<Integer,Items>();
	}
	public Map<Integer,Items> getMap() {
		return map;
	}
	public void setMap(Map<Integer,Items> map) {
		this.map = map;
	}
	/**
	 * 将商品放入购物车
	 * @param item
	 * @return
	 */
	public boolean add(Items item){
		if(map.containsKey(item.getProduct().getId())){//代表包含了此商品,则在数量上加一
			Items temp = map.get(item.getProduct().getId());
			temp.setNum(temp.getNum()+1);
			map.put(temp.getProduct().getId(),temp);
		}else{
			map.put(item.getProduct().getId(),item);//代表商品第一次加入购物车
		}
		return true;
	}
	/**
	 * 清空购物车
	 * @return
	 */
	public boolean clear(){
		map.clear();
		return true;
	}
	/**
	 * 指定删除某个商品
	 * @param id
	 * @return
	 */
	public boolean removePro(int id ){
		map.remove(id);
		return true;
	}
	
	/**
	 * 商品加1
	 * @return
	 */
	public boolean addOne(Items item){
		Items temp = map.get(item.getProduct().getId());
		temp.setNum(temp.getNum()+1);
		map.put(temp.getProduct().getId(),temp);
		return true;
	}
	
	/**
	 * 商品减1
	 * @return
	 */
	public boolean subOne(Items item){
		if(item.getNum()==1){
			removePro(item.getProduct().getId());
		}else{
			Items temp = map.get(item.getProduct().getId());
			temp.setNum(temp.getNum()-1);
			map.put(temp.getProduct().getId(),temp);
		}
		return true;
	}
}


商品列表页代码
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML >
<html>
  <head>
    <title>商品列表信息</title>
  </head>
  
  <body>
	<h3>商品列表信息</h3>
	<table width="100%" border="2">
	<tr>
		<td><input type="checkBox" id="all" onclick="allCheck(this)"/>全选</td>
			<td>商品编号</td>
			<td>商品名</td>
			<td>商品价格</td>
			<td>生产日期</td>
			<td>保质期</td>
			<td>单位</td>
	</tr>
	<c:forEach var="pro" items="${products}">
		<tr>
			<td><input type="checkBox" name="prochk" value="${pro.id }"/></td>
			<td>${pro.id }</td>
			<td>${pro.name }</td>
			<td>${pro.price }</td>
			<td>${pro.prodate }</td>
			<td>${pro.effdate }</td>
			<td>${pro.unit}</td>
		</tr>
	</c:forEach>
	
	</table>
	<br/>
	
	<div style="float:right;">
		[url=javascript:addPro();]加入购物车[/url]
		[url=cartlist.jsp ]跳转到购物车[/url]
	</div>
  </body>
  <script>
  		var xhr = null;
	
	function createXhr(){
		if(window.XMLHttpRequest){
			xhr = new XMLHttpRequest();
		}else{
			xhr = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	
	function addPro() {
		//获取需要加入购物车商品编号
		var ids = "";
		var prochk = document.getElementsByName("prochk");
		for (var i = 0; i < prochk.length; i++) {
			if (prochk[i].checked) {
				ids += prochk[i].value + ",";
			}
		}
		//连接后台,将商品编号,发送到后台
		createXhr();
		//打开连接
		xhr.open("post","ProServlet",true);
		//设置post请求的请求头
		xhr.setRequestHeader("content-type","application/x-www-form-urlencoded");
		//传送参数
		var data = "type=add&ids="+ids;
		xhr.send(data);
		xhr.onreadystatechange=function(){
			//判断服务器是否响应成功!
			if(xhr.readyState==4&&xhr.status==200){
				if(xhr.responseText=="ok"){
					alert("添加成功!");
				}else{
					alert("添加失败!");
				}
			}
		}
	}

	function allCheck(obj) {
		var checkBoxList = document.getElementsByName("prochk");
		if (obj.checked == true) {
			for (var i = 0; i < checkBoxList.length; i++) {
				checkBoxList[i].checked = true;
			}
		} else {
			for (var i = 0; i < checkBoxList.length; i++) {
				checkBoxList[i].checked = false;
			}
		}
	}
  </script>
</html>


购物车信息列表页面:
<%@ page language="java"  pageEncoding="utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML >
<html>
  <head>
    <title>购物车列表信息</title>
  </head>
  
  <body>
	<h3>购物车列表信息</h3>
	<table width="100%" border="2">
		<tr>
			<td>商品编号</td>
			<td>商品名称</td>
			<td>商品单价</td>
			<td>生产日期</td>
			<td>失效日期</td>
			<td>商品单位</td>
			<td>商品数量</td>
			<td>商品总额</td>
			<td>操作</td>
		</tr>
		<c:forEach var="item" items="${cart.map }">
			<tr>
				<td>
					${item.key }
				</td>
				<!-- Items -->
				<td>${item.value.product.name }</td>
				<td>${item.value.product.price }</td>
				<td>${item.value.product.prodate }</td>
				<td>${item.value.product.effdate }</td>
				<td>${item.value.product.unit }</td>
				<td>
					<input type="text" min="1" value="${item.value.num }" 
					style="width:30px" readonly/>
					<input type="button" value="+" onclick="javascript:addOne(${item.key})"/>
					<input type="button" value="-" onclick="javascript:subOne(${item.key})"/>
				</td>
				<td>${item.value.product.price*item.value.num }</td>
				<td>
					<input type="hidden" name="id" value="${item.key }"/>
					[url=javascript:deleteProductItem(${item.key});]删除[/url]
				</td>
			</tr>
		</c:forEach>
	</table>
	<br>
	<div style="float: right;">
		[url=ProServlet?type=clear]清空购物车[/url] [url=ProServlet]返回[/url]
	</div>
</body>
<script>
	var xhr=null;
	//创建引擎对象
  	function createXhr(){
  		if(window.XMLHttpRequest){
  			xhr=new XMLHttpRequest();
  		}else{
  			xhr=new ActiveXObject("Microsoft.XMLHTTP");
  		}
  	}
	//删除单个商品
	   function deleteProductItem(id){
		 	if(confirm("确定删除该商品吗?")){
		 		createXhr();
		  		xhr.open("get","ProServlet?type=delete&id="+id,true);
		  		xhr.send();
		  		xhr.onreadystatechange=function(){
		  			if(xhr.readyState==4&&xhr.status==200){
		  				if(xhr.responseText=="ok"){
		  					alert("删除成功!");
		  					window.location.reload();
		  				}else{
							alert("删除失败!");
						}
		  			}  		
		  		}
		 	}	
	  	}
	  	//商品数量加1
	  	function addOne(id){
	  		createXhr();
	  		xhr.open("get","ProServlet?type=addOne&id="+id,true);
	  		xhr.send(null);
	  		xhr.onreadystatechange=function(){
	  			if(xhr.readyState==4&&xhr.status==200){
	  				if(xhr.responseText=="ok"){
						alert("添加成功!");
						window.location.reload();
					}else{
						alert("添加失败!");
					}
	  			}
	  		}
	  	}
	  	//商品数量减1
	  	function subOne(id){
	  		createXhr();
	  		xhr.open("get","ProServlet?type=subOne&id="+id,true);
	  		xhr.send(null);
	  		xhr.onreadystatechange=function(){
	  			if(xhr.readyState==4&&xhr.status==200){
	  				if(xhr.responseText=="ok"){
						alert("商品减一!");
						window.location.reload();
					}else{
						alert("失败!");
					}
	  			}
	  		}
	  	}
</script>
</html>


pproduct实体类:

public class Product implements Serializable{
	private static final long serialVersionUID = 1L;
	private int id;
	private String name;
	private double price;
	private Date prodate;
	private Date effdate;
	private String unit;
	public Product() {
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public double getPrice() {
		return price;
	}
	public void setPrice(double price) {
		this.price = price;
	}
	public Date getProdate() {
		return prodate;
	}
	public void setProdate(Date prodate) {
		this.prodate = prodate;
	}
	public Date getEffdate() {
		return effdate;
	}
	public void setEffdate(Date effdate) {
		this.effdate = effdate;
	}
	public String getUnit() {
		return unit;
	}
	public void setUnit(String unit) {
		this.unit = unit;
	}
}


item实体类:
public class Items implements  Serializable{
	private static final long serialVersionUID = 1L;
	private Product product;
	private int num;
	public Items() {
	}
	public Product getProduct() {
		return product;
	}
	public void setProduct(Product product) {
		this.product = product;
	}
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
}
原文链接:https://www.f2er.com/ajax/161286.html

猜你在找的Ajax相关文章