<%
String sql="select * from cart ";
PreparedStatement pstat=conn.prepareStatement(sql);
ResultSet rs=pstat.executeQuery();
//商品展示
String id,name,price,num,count,IMG;
while(rs.next()){
id=rs.getString("SP_NO").trim();
name=rs.getString("SP_NAME").trim();
price=rs.getString("SP_PRICE").trim();
num=rs.getString("BUY_NUM").trim();
count=rs.getString("COUNT").trim();
IMG=rs.getString("IMG").trim();
session.setAttribute("name1",name);
%>
<tr>
<td class="checkbox"><input class="check" type="checkbox" /></td>
<td style="padding-left:20px;padding-right:20px;"><img width=90px height=90px src="<%=IMG%>" ></td>
<td style="width:300px;text-align:center;"><%=name %></td>
<td style="width:150px;"><%=price %></td>
<td style='width:150px;'><input type=number style="width:60px;" value="<%=num%>" onChange=updateNum(id,this.value,price) ></td>
<td style='width:150px;' class="count"><%=count%></td>
<td style='width:150px;'><a href="buy.jsp?op=del&id=<%=id %>" style="color:#000000;text-decoration: none;">删除商品</a></td>
</tr>
<%} %>
<div id="money">
<table id="all" width="300px;">
<thead>
<tr ><th colspan="2" style="text-align:left;">购物车合计</th></tr>
</thead>
<tbody >
<tr> <td >购物车小计 </td> <td><span class="getPrice" ></span></td></tr>
<tr> <td >运费</td> <td>免费运输</td></tr>
<tr> <td >购物车合计</td> <td ><span class="getPrice" ></span></td> </tr>
</tbody>
</table>
<button class="list" style="margin-left:-200px;" name="clean">结账</button>
</div>
function getPrices(){
//获得各个商品的单独总价
var counts = document.getElementsByClassName("count");
var sum = 0;
for( i=0;i < counts.length;i++){
sum += Number(counts[i].innerText);
}
return sum;
}
//将getPrices函数获得dom元素将计算出的总价写入对应的td表格
var cartPrice = getPrices();
function writePrice(sum){
var prices = document.getElementsByClassName("getPrice");
for( i=0;i<prices.length;i++){
prices[i].innerHtml = sum;
}
}
function updateNum(id,num,price){
//调用已定义好的writePrice函数计算出购物车的总价格,并输入到页面对应的表格上
writePrice(cartPrice);
//定义一个新的url将页面中的值传入buy.jsp业务处理页面
var url="buy.jsp?op=update&id="+id+"&num="+num2+"&price="+price;
//window.Location方法让当前页面跳转到指定的地址
window.location=url;
}
function initPrice(){
writePrice(cartPrice);
}
initPrice();
<%
//更新商品信息功能
if(op.equals("update")){
int id=Integer.parseInt(request.getParameter("id"));
int num2=Integer.parseInt(request.getParameter("num2"));
double price=Double.parseDouble(request.getParameter("price"));
String sql="update cart set BUY_NUM =?,COUNT=? where sp_NO=?";
PreparedStatement pstat=conn.prepareStatement(sql);
pstat.setInt(1,num2);
pstat.setString(2,new Double(price*num2).toString());
pstat.setInt(3,id);
pstat.executeUpdate();
pstat.close();
conn.close();
response.sendRedirect("cart.jsp");
}; %>