【发布时间】:2017-09-02 20:05:17
【问题描述】:
我没有使用产品 ID,而是为购物车中的每个商品设置了一个索引,从 0 开始。购物车中的每个商品都有自己的从购物车中删除/删除按钮。单击该按钮时,该值通过 ajax 发布到 php 脚本:
if(isset($_POST['indexToRemove']) && $_POST['indexToRemove'] !== "") {
$key_to_remove = $_POST['indexToRemove'];
if(count($_SESSION['cart_array']) <=1) {
unset($_SESSION['cart_array']);
} else {
unset($_SESSION['cart_array'][$key_to_remove]);
}
}
如果我单击时 console.log() indexToRemove,它会在控制台中显示正确的值。但是,该项目永远不会从会话中删除,并且控制台中没有错误来帮助进行故障排除。
这里是 jQuery:
$("body").on("click", ".removeItem", function () {
var indexToRemove = $(this).data('itr');
var div = $(this).parents("div.hr");
$.ajax({
url: 'functions/show-cart.php',
type: 'POST',
dataType: 'json',
data: {
indexToRemove: indexToRemove
},
beforeSend: function () {
$(div).html("<img src='images/spinner.gif'>");
$("#total").empty();
},
})
.done(function (data) {
$(div).fadeOut();
show_cart();
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
})
})
加入购物车代码:
$quantity = 1;
$product_id = $_POST['id'];
$colour = $_POST['colour'];
$size = $_POST['size'];
$key = "{$product_id}.{$colour}.{$size}";
if (empty($_SESSION['cart_array'][$key])) {
$_SESSION['cart_array'][$key] = array(
"item_id" => $product_id,
"quantity" => $quantity,
"colour" => $colour,
"size" => $size,
);
}
else {
$_SESSION['cart_array'][$key]['quantity'] += $quantity;
}
显示购物车物品的php代码:
if(!isset($_SESSION['cart_array'])) {
$itemsInCart = 0;
$response['total'] = 0;
echo json_encode($response);
} else {
$featured = "Yes";
$i=0;
foreach($_SESSION['cart_array'] as $each_item) {
$item_id = $each_item['item_id'];
$colour = $each_item['colour'];
$size = $each_item['size'];
$stmt = $link->prepare("SELECT `product_name`, `price`, `pic_name` FROM `products` as `p` INNER JOIN `product_images` as `pi` ON p.`id` = pi.`product_id` WHERE p.`id` = ? AND `featured` = ?");
$stmt->bind_param("is", $item_id, $featured);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if($numRows > 0) {
while($row = $result->fetch_assoc()) {
$product_name = sanitize($row['product_name']);
$price = sanitize(money_format('%.2n', $row['price']));
$subtotal = money_format('%.2n', $each_item['quantity'] * $price);
$pic_name = $row['pic_name'];
$cartTotal = $subtotal + $cartTotal;
$quantity = $each_item['quantity'];
$cart_details[] = array(
"product_name" => $product_name,
"price" => $price,
"subtotal" => $subtotal,
"pic_name" => $pic_name,
"each_item" => $quantity,
"item_id" =>$item_id,
"i" => $i,
"colour" => $colour,
"size" => $size,
);
$i++;
}
}
$stmt->close();
}
$response['total'] = $cartTotal;
$response['cart'] = $cart_details;
echo json_encode($response);
}
【问题讨论】: