以下是一个简单的购物车功能示例:

  1. 首先建立一个购物车页面,包括商品列表和一个添加到购物车的按钮:
<?php
// 商品列表
$products = array(
    array("id" => 1, "name" => "商品1", "price" => 10),
    array("id" => 2, "name" => "商品2", "price" => 20),
    array("id" => 3, "name" => "商品3", "price" => 30),
    array("id" => 4, "name" => "商品4", "price" => 40),
    array("id" => 5, "name" => "商品5", "price" => 50),
);

// 显示商品列表和添加到购物车按钮
foreach ($products as $product) {
    echo '<div>';
    echo '<span>' . $product['name'] . '</span>';
    echo '<span>' . $product['price'] . '元</span>';
    echo '<button onclick="add_to_cart(' . $product['id'] . ')">添加到购物车</button>';
    echo '</div>';
}
?>
  1. 接下来,在页面底部添加一个购物车列表,用于显示当前购物车中的商品和总价:
<div id="cart">
    <h2>购物车</h2>
    <ul id="cart-list"></ul>
    <p>总价:<span id="cart-total">0</span>元</p>
</div>
  1. 使用ajax编写一个添加商品到购物车的函数:
function add_to_cart(id) {
    // 发送ajax请求,将商品id加入购物车
    $.ajax({
        url: 'add_to_cart.php',
        type: 'POST',
        data: { id: id },
        success: function(response) {
            // 更新购物车列表和总价
            $('#cart-list').html(response.cart_list);
            $('#cart-total').text(response.cart_total);
        },
        error: function() {
            alert('添加失败');
        }
    });
}
  1. 编写一个处理添加到购物车请求的php脚本:
<?php
session_start();

// 将商品id加入购物车
if (isset($_POST['id'])) {
    $id = $_POST['id'];
    $_SESSION['cart'][$id] = 1;
}

// 构造购物车列表和总价
$cart_list = '';
$cart_total = 0;
if (isset($_SESSION['cart'])) {
    foreach ($_SESSION['cart'] as $id => $quantity) {
        $product = $products[$id - 1];
        $cart_list .= '<li>' . $product['name'] . ' × ' . $quantity . '</li>';
        $cart_total += $product['price'] * $quantity;
    }
}

// 返回购物车列表和总价
echo json_encode(array(
    'cart_list' => $cart_list,
    'cart_total' => $cart_total
));
?>
  1. 最后,在购物车页面中引入jquery和上面编写的函数和脚本:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function() {
    // 添加商品到购物车
    function add_to_cart(id) {
        // ...
    }

    // 显示购物车列表和总价
    $.ajax({
        url: 'get_cart.php',
        success: function(response) {
            $('#cart-list').html(response.cart_list);
            $('#cart-total').text(response.cart_total);
        },
        error: function() {
            alert('获取购物车失败');
        }
    });
});
</script>
<?php include 'add_to_cart.php'; ?>
``
用php写一个购物车功能

原文地址: https://www.cveoy.top/t/topic/eplI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录