我正在购物车上执行一项任务,其中当我单击“add_cart”按钮时。它应该在购物车图标上显示购物车中存在的商品总数。在我将商品添加到购物车后,它会显示正确的计数,但当我单击 cart_details 页面然后按后退按钮时,问题就出现了。甚至在我将商品添加到购物车之前它就显示旧数字。
$('body').on('click', '.cart', function () {
id = $(this).attr("id");
website_id = id.replace("cart_", "");
advertiser_id = <?php echo $advertiser_id; ?>;
cart_icon_class = $(this).find("img").attr("class");
if(cart_icon_class == "blank_cart"){
action = "add";
}else{
action = "delete";
}
$.ajax({
type: 'POST',
url: "{{ route('cartstore') }}",
data: {id: website_id, advertiser_id: advertiser_id, action:action, website_id:website_id},
dataType: 'json',
success: function (data) {
if(action == "add"){
// console.log(data);
$("#cart_span").text(data['carts']);
$("#wishlist_span").text(data['wish']);
$(".box no-border").hide();
$("#cart-success").show();
$("#cart_icon_" + data["website_id"]).attr("src","{{URL::asset('assets/images/fas-fa-shopping-cart.png')}}");
$("#cart_icon_" + data["website_id"]).removeClass('blank_cart');
$("#cart_icon_" + data["website_id"]).addClass('filled_cart');
$("#wish_icon_" + data["website_id"]).removeClass('fas fa-heart');
$("#wish_icon_" + data["website_id"]).addClass('far fa-heart');
setTimeout(function () {
$('#cart-success').hide();
}, 1500);
}
else
{
// console.log(data);
$("#cart_span").text(data['carts']);
$("#wishlist_span").text(data['wish']);
$(".box no-border").hide();
$("#cart-danger").show();
$("#cart_icon_" + data["website_id"]).attr("src","{{URL::asset('assets/images/far-fa-shopping-cart.png')}}");
$("#cart_icon_" + data["website_id"]).removeClass('filled_cart');
$("#cart_icon_" + data["website_id"]).addClass('blank_cart');
setTimeout(function () {
$('#cart-danger').hide();
}, 1500);
}
$("#cart_span").show();
$("#wishlist_span").show();
if (data['wish'] == 0) {
$("#wishlist_span").css("display", "none");
}
if (data['carts'] == 0) {
$("#cart_span").css("display", "none");
}
}, error: function (error) {
alert("Something went wrong please try again.");
}
});
});
if(!!window.performance && window.performance.navigation.type == 2){
window.location.reload();}
这不会重新加载您的页面两次,并且单击后退按钮后您还将获得更新的数据。
这应该在所有浏览器上都能正常工作
// force browser to refresh when you click on previous or next button arrow of browser
window.addEventListener( "pageshow", function ( event ) {
var historyTraversal = event.persisted ||
( typeof window.performance != "undefined" &&
window.performance.navigation.type === 2 );
if ( historyTraversal ) {
// Handle page restore.
window.location.reload();
}
});
之后:
success: function(data) {
if (action == "add") {
window.location.reload();
}
}
或者,如果您希望避免页面重新加载,您可以选择接收 JSON 数据来响应此请求,其中包含更新的信息。然后您可以分配并显示该数据。如果可行,您还可以重复使用发送的初始数据来更新视图。