1
而不是使用产品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);
}
如果我只有1项,然后它的工作原理和项目被删除 – user8463989
我不知道如何检查你的要求。如果我console.log()出indexToRemove,第一个购物车项目的值为0,seance项目值为1,第三个项目值为2,依此类推 – user8463989
@ user8463989对不起,您可以在PHP中转储$ key_to_remove的值,你的数组和测试密钥是否有效一样?原因是因为我看到** $ key =“{$ product_id}。{$ color}。{$ size}”; **并且我认为这不是一个数字。 – gaetanoM