<body>
<!-- 加入span的目的是为了定位 -->
<div id="cartstatus">
您已经将
<span id="bookName"></span>加入到购物车中,购物车中有
<span id="totalBookNumber"></span>本书,总价格是
<span id="totalMoney"></span>
</div>
<br>
<br>
java
<a
href="${pageContext.request.contextPath}/addToCart?id=java&price=100">加入购物车</a>
<br>
ajax
<a
href="${pageContext.request.contextPath}/addToCart?id=ajax&price=200">加入购物车</a>
<br>
jquery
<a
href="${pageContext.request.contextPath}/addToCart?id=jquery&price=300">加入购物车</a>
<br>
</body>
<!--${pageContext.request.contextPath}获取该项目的绝对路径 -->
public class AddToCartServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//1:获取请求参数 id(bookName),price
String bookName =request.getParameter("id");
int price =Integer.parseInt(request.getParameter("price"));
//2:获取购物车对象,在session中
ShoppingCart sc=(ShoppingCart) request.getSession().getAttribute("sc");
if(sc==null){
sc=new ShoppingCart();
request.getSession().setAttribute("sc",sc);
}
//3;将点击的对象加入到购物车中
sc.addToCart(bookName, price);
//4:准备响应的Json对象:{""bookName"":"totalBookNumber","totalMoney" }
//若从服务器端返回json对象,则属性名必须使用双引号!!
StringBuilder sBuilder=new StringBuilder();
sBuilder.append("{")
.append("\"bookName\":\""+bookName+"\"")
.append(",")
.append("\"totalBookNumber\":\""+sc.getTotalBookNumber()+"\"")
.append(",")
.append("\"totalMoney\":\""+sc.getTotalMoney()+"\"")
.append("}");
//响应json请求
response.setContentType("text/javascript");
response.getWriter().print(sBuilder.toString());
}
}
上述中的用StringBuilder来拼接JSON字符串的方式可以借助第三方开源Jackson来简化实现:
String jsonStr=null;
ObjectMapper objectMapper=new ObjectMapper();
jsonStr=objectMapper.writeValueAsString(sc);
<head>
<!--${pageContext.request.contextPath}获取该项目的绝对路径 -->
<script type="text/javascript"
src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function(){
var isHasCart="${sessionScope.sc==null}";
if(isHasCart=="true"){
$("#cartstatus").hide();//隐藏显示的元素
}else{
$("#cartstatus").show(); //显示隐藏的匹配元素
$("#bookName").text("${sessionScope.sc.bookName}");
$("#totalBookNumber").text("${sessionScope.sc.totalBookNumber}");
$("#totalMoney").text("${sessionScope.sc.totalMoney}");
}
$("a").click(function(){
$("#cartstatus").show();
var url=this.href; //url属性
var agrs={"time":new Date()}; //时间戳
$.getJSON(url,agrs,function(data){
$("#bookName").text(data.bookName);
$("#totalBookNumber").text(data.totalBookNumber);
$("#totalMoney").text(data.totalMoney);
});
return false;
});
});
</script>
</head>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有