【问题描述】
下列代码分别是两个文件:购物车首页页面
购物车控制器页面
怎么在购物车首页实现使用button按钮对session中的商品数量进行修改,购物车首页的商品数据来自于session。
每个商品的id作为下标存储在session中。
见下图。
请讲解,谢谢
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>购物车首页</title>
<load file="__HOMEJS__/jquery-1.8.3.js" />
</head>
<body>
<table border="1" width="800" align="center">
<tr>
<th align="center">商品</th>
<th align="center">单价</th>
<th align="center">数量</th>
<th align="center">公司</th>
<th align="center">小计</th>
<th align="center">操作</th>
</tr>
<foreach name="result" item="vo">
<tr>
<td align="center"><img src='<{$vo.picname}>' /></td>
<td align="center">¥<{$vo.price}></td>
<td align="center"><button >-</button> <{$vo.m}> <button>+</button></td>
<td align="center"><{$vo.company}></td>
<td align="center">¥<{$vo['price']*$vo['m']}></td>
<td>
<a href="__CONTROLLER__/delgood/id/<{$vo.id}>">删除</a>
</td>
</tr>
</foreach>
</table>
<!-- 模拟商品添加 -->
<a href="__CONTROLLER__/addcar/id/5">添加商品</a>
<br/>
<a href="__CONTROLLER__/addcar/id/2">添加商品</a>
<br/>
<a href="__CONTROLLER__/clearcar">清空购物车</a>
</body>
</html>
<?php
namespace Home\Controller;
use Think\Controller;
class BuycarController extends CommonController{
public function index(){
//$_SESSION = array();
if(!empty($_SESSION['shoplist'])){
$result = $_SESSION['shoplist'];
$this->assign('result',$result);
}
$this->display();
}
public function addcar(){
$id = I('get.id');
$m = M('home_goods');
$res = $m->where('id='.$id)->find();
if(empty($res)){
die("未找到要添加的商品,请再次确认");
}
$res['m'] = 1;
if(empty($_SESSION['shoplist'][$id])){
$_SESSION['shoplist'][$id] = $res;
$this->success('成功加入购物车',U("Buycar/index"),1);
}else{
$_SESSION['shoplist'][$id]['m']+=1;
$this->success('成功加入购物车',U("Buycar/index"),1);
}
}
public function modm(){
$num = I('post.num');
$id = I('post.num2');
if($num<2){
$num = 2;
}
$num--;
$_SESSION['shoplist'][$id]['m'] = $num;
echo $num;
}
public function modp(){
$num = I('post.num');
$id = I('post.num2');
$num++;
$_SESSION['shoplist'][$id]['m'] = $num;
echo $num;
}
public function clearcar(){
$_SESSION['shoplist'] = array();
echo"<script>alert('购物车已清空');window.location='index';</script>";
}
public function delgood(){
$id = I('get.id');
unset($_SESSION['shoplist'][$id]);
$this->success('成功删除',U("Buycar/index"),1);
}
}