php购物车实现代码
ShopCar.php
复制代码 代码如下:
class Shopcar
{
//商品列表
public $productList=array();
/**
*
* @param unknown_type $product 传进来的商品
* @return true 购物车里面没有该商品
*/
public function checkProduct($product)
{
for($i=0;$iproductList);$i++ )
{
if($this->productList[$i]['name']==$product['name'])
return $i;
}
return -1;
}
//添加到购物车
public function add($product)
{
$i=$this->checkProduct($product);
if($i==-1)
array_push($this->productList,$product);
else
$this->productList[$i]['num']+=$product['num'];
}
//删除
public function delete($product)
{
$i=$this->checkProduct($product);
if($i!=-1)
array_splice($this->productList,$i,1);
}
//返回所有的商品的信息
public function show()
{
return $this->productList;
}
}
productList.html
复制代码 代码如下:
Insert title herefunction buy(i)
{
var num=$(':input[name=num]')[i].value;
var name=$('[name=name]')[i].innerHTML;
var price=$('[name=price]')[i].innerHTML;
alert(num+name+price);
$.ajax({
type:'post', //传送的方式,get/post
url:'index.php', //发送数据的地址
cache:'false',
data:'num='+num+"&name="+name+"&price="+price,
success:function(data)
{
alert(data);
}
})
}
商品编号 | 商品名称 | 价格 | 数量 | 购买 |
0 | 商品1 | 1 | 购买 | |
1 | 商品2 | 2 | 购买 | |
2 | 商品3 | 1 | 购买 | |
3 | 商品4 | 1 | 购买 |
index.php
复制代码 代码如下:
require 'Shopcar.class.php';
session_start();
$name=$_POST['name'];
$num=$_POST['num'];
$price=$_POST['price'];
$product=array('name'=>$name,'num'=>$num,'price'=>$price);
print_r($product);
if(isset($_SESSION['shopcar']))
$shopcar=unserialize($_SESSION['shopcar']);
else
$shopcar=new Shopcar();
$shopcar->add($product);
$_SESSION['shopcar']=serialize($shopcar);
show.php
复制代码 代码如下:
商品编号 | 商品名称 | 价格 | 数量 |
require 'Shopcar.class.php';
session_start();
$shopcar=unserialize($_SESSION['shopcar']);
print_r($shopcar);
$productList=$shopcar->productList;
foreach ($productList as $product){
?>
1<?php echo $product['name']?><?php echo $product['price']?>' />相关阅读:
javascript对象与数组参考大全(5)
js实现的八点拖动修改div大小的代码
优化Apache,让网站速度更快
javascript模拟的Ping效果代码 (Web Ping)
CSS命名规范和CSS书写规范及方法
获取ACCESS2000数据库中所有表的名称
找回被删除的vista的自带驱动
Access如何维护表的参照完整性
制作简单实用的调色板工具
javascript trim 去空格函数实现代码
ASP 多关键词查询实例代码
vbs 注册表操作代码(添加删除)
Linux Shell变量使用
CMS Made Simple内容管理系统安装配置