点击“添加到购物车”后,购物车中会添加1个商品。购物车中的每个商品都有一个加号和减号,因此用户可以增加1或减少1.如果单击加号,它应该添加一个到单击的特定项目。目前,这仅在首次点击时有效,而不是之后的点击。我不确定问题是jquery还是php。
$("body").on("click", ".cartPlus", function () {
var itemToEdit = $(this).data('id');
var qty = $(this).data('qty');
var newQty = qty + 1;
$.ajax({
url: 'functions/show-cart.php',
type: 'POST',
dataType: 'json',
data: {
itemToEdit: itemToEdit,
newQty: newQty
},
beforeSend: function () {
$(".price-xs").empty();
},
})
.done(function (data) {
$.each(data.cart, function (index, item) {
console.log(item.each_item);
});
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log(textStatus + ': ' + errorThrown);
console.warn(jqXHR.responseText);
});
});
if(isset($_POST['itemToEdit']) && $_POST['itemToEdit'] != "") {
$i = 0;
$item_to_edit = $_POST['itemToEdit'];
$quantity = $_POST['newQty'];
foreach($_SESSION['cart_array'] as $each_item) {
$i++;
while(list($key, $value) = each($each_item)) {
if($key == "item_id" && $value == $item_to_edit) {
array_splice($_SESSION['cart_array'], $i-1, 1, array(array("item_id" => $item_to_edit, "quantity" => $quantity)));
}
}
}
}
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'];
$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
);
$i++;
}
}
$stmt->close();
}
$response['total'] = $cartTotal;
$response['cart'] = $cart_details;
echo json_encode($response);
}
答案 0 :(得分:0)
请更新以下示例中的数据量。
var num = $('#foo').data("num") + 1;
console.log(num);
$('#foo').data('num', num);
console.log(num);