产品数据无法通过Ajax从product.php传递到cart.php问题排查
问题场景
我有存储产品信息的数据库,以及展示全量产品的shop.php页面。点击页面内的特定产品会跳转至product.php加载对应产品数据,但点击「加入购物车」按钮后,购物车未正常显示添加的产品,怀疑是product.php未正确发送单个产品数据。
product.php 代码
session_start(); require_once "connection.php"; $product_id = $_GET['product_id'] ?? null; if ($product_id) { $sql_product = "SELECT picture, product_name, price, Size FROM product WHERE product_id = ?"; $stmt = mysqli_prepare($conn, $sql_product); mysqli_stmt_bind_param($stmt, "i", $product_id); mysqli_stmt_execute($stmt); $result_product = mysqli_stmt_get_result($stmt); if ($result_product && mysqli_num_rows($result_product) > 0) { $row_product = mysqli_fetch_assoc($result_product); $product_name = $row_product['product_name']; $product_price = $row_product['price']; $product_picture = $row_product['picture']; } }
Ajax 加入购物车代码(位于product.php前端)
document.getElementById("addToCartBtn").addEventListener("click", function(event) { event.preventDefault(); var productName = "<?php echo $product_name; ?>"; var productPrice = "<?php echo $product_price; ?>"; var productPicture = "<?php echo $product_picture; ?>"; var quantity = document.querySelector("select[name='quantity']").value; var size = document.getElementById("sizeSelect").value; var xhr = new XMLHttpRequest(); xhr.open("POST", "cart.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { console.log(xhr.responseText); } }; xhr.send("product_name=" + encodeURIComponent(productName) + "&product_price=" + encodeURIComponent(productPrice) + "&product_picture=" + encodeURIComponent(productPicture) + "&quantity=" + encodeURIComponent(quantity) + "&size=" + encodeURIComponent(size)); });
cart.php 代码
session_start(); // 原代码缺失,必须添加才能操作SESSION if (!isset($_SESSION['cart'])) { $_SESSION['cart'] = array(); } if (isset($_GET['remove_item'])) { $remove_index = $_GET['remove_item']; if (array_key_exists($remove_index, $_SESSION['cart'])) { unset($_SESSION['cart'][$remove_index]); } } // 原代码缺失:处理添加购物车的POST请求逻辑 if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['product_name'])) { $cart_item = array( 'product_name' => $_POST['product_name'], 'product_price' => $_POST['product_price'], 'product_picture' => $_POST['product_picture'], 'quantity' => $_POST['quantity'], 'size' => $_POST['size'] ); $_SESSION['cart'][] = $cart_item; echo "商品已添加到购物车"; exit; } if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['index']) && isset($_POST['quantity'])) { $index = $_POST['index']; $quantity = $_POST['quantity']; if (array_key_exists($index, $_SESSION['cart'])) { $_SESSION['cart'][$index]['quantity'] = $quantity; echo $_SESSION['cart'][$index]['quantity'] * $_SESSION['cart'][$index]['product_price'] . '€'; } else { echo "Error"; } exit; } ?> <!-- 购物车列表渲染代码 --> <tr> <td><a href="cart.php?remove_item=<?php echo $index; ?>"><i class="fa-solid fa-circle-xmark"></i></a></td> <td><img src="<?php echo $item['product_picture']; ?>" alt="" style="width: 100px; height: auto;"></td> <td><?php echo $item['product_name']; ?></td> <td><?php echo $item['size']; ?></td> <td><?php echo $item['product_price']; ?>€</td> <td> <input type="number" id="quantity_<?php echo $index; ?>" value="<?php echo $item['quantity']; ?>" min="1" onchange="updateQuantity(<?php echo $index; ?>, this.value)"> </td> <td id="total_<?php echo $index; ?>"><?php echo $item['quantity'] * $item['product_price']; ?>€</td> </tr>
问题排查与修复
product.php 变量安全处理
若$product_id无效或数据库查询无结果,$product_name等变量会未定义,导致Ajax发送空数据。需补充默认值与错误跳转:// 在查询逻辑后添加 } else { header("Location: shop.php"); exit; } // 给变量设置默认值,避免未定义报错 $product_name = $row_product['product_name'] ?? ''; $product_price = $row_product['price'] ?? 0; $product_picture = $row_product['picture'] ?? '';cart.php 核心逻辑补全
原代码完全缺失接收添加购物车请求的逻辑,这是购物车无数据的主要原因,需添加上述代码中处理添加购物车的POST请求逻辑部分;同时必须在文件开头添加session_start(),否则无法读写购物车SESSION数据。Ajax 数据校验优化
前端可添加非空校验,避免发送无效请求:if (!productName || !productPrice || !quantity || !size) { alert("商品信息不完整,无法添加到购物车"); return; }
内容的提问来源于stack exchange,提问作者Roland Toth
相关产品推荐
相关产品推荐

