![](/img/trans.png)
[英]When adding product to cart default options are added for the product, but not selected ones
[英]Getting Shopping cart quanitity counter to show product added right when selected to add
我的网站上有一个购物车数量计数器,直到重新加载页面或转到其他页面时,才显示产品已添加。 我要数量计数器立即显示正在添加的产品。 我在每一页上都有这个数量计数器。 我确定可以用Ajax添加类似的内容,但是我什至不知道如何开始。
我现在将其设置如下:
我的网站上每个页面上都有一个要求页面,名为loadProducts.php。
它包含以下内容:
//Shopping Cart Quantity Count
if(isset($_SESSION['shopping_cart']) && is_array($_SESSION['shopping_cart'])) {
$totalquantity = 0;
foreach($_SESSION['shopping_cart'] AS $product) {
$totalquantity = $totalquantity + $product['quantity'];
}
}
else {
$totalquantity = 0;
}
将物品放入购物车后,是否有办法立即进行装载? 如果您想了解我的意思,我的网站是buyfarbest.com。 如果转到产品选项卡,然后添加产品。 添加该数量后,您必须转到另一个页面以配置该数量。
您可以使用以下代码使用javascript动态请求此数据。
cartQuantity.php
<?php
$totalQuantity = 0;
$success = false; //If session is not set, leave this as false
if(isset($_SESSION['shopping_cart']) && is_array($_SESSION['shopping_cart'])) {
foreach($_SESSION['shopping_cart'] AS $product) {
$totalquantity += $product['quantity']; //Increment total quantity by product quantity
}
$success = true; //Session is set, and quantity has been incremented
}
header('Content-type: application/json'); //jquery will automatically parse what follows as a json array. Handy!
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past
echo json_encode(array('success'=>$success, 'shopping_cart_quantity'=>$totalQuantity));
并在您的html中:
<div id='shoppingCartCounter'></div>
<script type='text/javascript'>
function updateCartCounter() {
$.get('path/to/cartQuantity.php', function(json) {
var shoppingCartCounter = $('#shoppingCartCounter'); //Make a local variable to reference the appropriate div
if(json['success']) { shoppingCartCounter.html(json['shopping_cart_quantity']) } //populate it with the count
else shoppingCartCounter.html(''); //or erase the number altogether
});
}
</script>
现在,无论何时调用updateCartCounter()
,计数器都将执行此操作。 您可以通过以下两种方式之一或全部执行此操作:
间隔(效率不高)
setInterval(function(){ updateCartCounter(); }, 10000); //Update the counter every 10 seconds
或在购物车操作功能内
function someCartOperation() { //This is whatever your application uses for adding/removing stuff in the cart
/*
Do all your important cart stuff
*/
updateCartCounter(); //You're done working on the cart, now update the counter
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.