PHP头条
热点:

一个简单的php+Ajax购物车程序代码(1/2)


本文章来给大家推荐一个不错的购物车效果,这里主要求包括了几个东西,一个是购物车类用php写的, 还有一个Ajax操作用到了jquery,还有一个jquery插件thickbox了,下面我们来看看。

购物车类:shop_cart.php
购物车的操作:cart_action.php
首页:index.html
Ajax操作用到了jquery,还有一个jquery插件thickbox

不多说了你可以先看看效果示例
shop_cart.php当然是购物车的核心,但是这个类很简单,因为他又引进了cart_action.php用于对外操作。所以这个类显得相当精简。
购物车类shop_cart.php

代码如下

cart_name = $name;
$this->items = $_SESSION[$this->cart_name];
}

/**
* setItemQuantity() - Set the quantity of an item.
*
* @param string $order_code The order code of the item.
* @param int $quantity The quantity.
*/
function setItemQuantity($order_code, $quantity) {
$this->items[$order_code] = $quantity;
}

/**
* getItemPrice() - Get the price of an item.
*
* @param string $order_code The order code of the item.
* @return int The price.
*/
function getItemPrice($order_code) {
// This is where the code taht retrieves prices
// goes. We'll just say everything costs $9.99 for this tutorial.
return 9.99;
}

/**
* getItemName() - Get the name of an item.
*
* @param string $order_code The order code of the item.
*/
function getItemName($order_code) {
// This is where the code that retrieves product names
// goes. We'll just return something generic for this tutorial.
return 'My Product (' . $order_code . ')';
}

/**
* getItems() - Get all items.
*
* @return array The items.
*/
function getItems() {
return $this->items;
}

/**
* hasItems() - Checks to see if there are items in the cart.
*
* @return bool True if there are items.
*/
function hasItems() {
return (bool) $this->items;
}

/**
* getItemQuantity() - Get the quantity of an item in the cart.
*
* @param string $order_code The order code.
* @return int The quantity.
*/
function getItemQuantity($order_code) {
return (int) $this->items[$order_code];
}

/**
* clean() - Cleanup the cart contents. If any items have a
* quantity less than one, remove them.
*/
function clean() {
foreach ( $this->items as $order_code=>$quantity ) {
if ( $quantity < 1 ) unset($this->items[$order_code]);
}
}

/**
* save() - Saves the cart to a session variable.
*/
function save() {
$this->clean();
$_SESSION[$this->cart_name] = $this->items;
}
}

?>

对于cart_action,他实现了shop_cart类与index的中间作用,用于更新,删除,增加商品的操作。
cart_action.php

代码如下

getItemQuantity($_GET['order_code'])+$_GET['quantity'];
$Cart->setItemQuantity($_GET['order_code'], $quantity);
}else{

if ( !empty($_GET['quantity']) ) {
foreach ( $_GET['quantity'] as $order_code=>$quantity){
$Cart->setItemQuantity($order_code, $quantity);
}
}

if ( !empty($_GET['remove']) ) {
foreach ( $_GET['remove'] as $order_code ) {
$Cart->setItemQuantity($order_code, 0);
}
}
}
$Cart->save();

header('Location: cart.php');

?>

还有就是index.html实现对外的操作,也就是添加操作

代码如下





Shopping Cart

相关文章

PHP之友评论

今天推荐