Как добавить товар в корзину без перезагрузки страницы?
Я хочу добавить товар в корзину без перезагрузки страницы каждый раз, есть ли способ сделать это, который не будет медленным? если да, то как мне это исправить? также я не очень хорошо разбираюсь в javascript, так что если вы можете немного объяснить, я буду очень признателен за помощь, спасибо!
ссылка на остальной основной код:
https://gist.github.com/StackingUser/34b682b6da9f918c29b85d6b09216352
шаблон:
{% load static %}
<link rel="stylesheet" href="{% static 'store/css/shop.css' %}" type="text/css">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="text/javascript">
var user = '{{request.user}}'
function getToken(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getToken('csrftoken');
function getCookie(name) {
// Split cookie string and get all individual name=value pairs in an array
var cookieArr = document.cookie.split(";");
// Loop through the array elements
for(var i = 0; i < cookieArr.length; i++) {
var cookiePair = cookieArr[i].split("=");
/* Removing whitespace at the beginning of the cookie name
and compare it with the given string */
if(name == cookiePair[0].trim()) {
// Decode the cookie value and return
return decodeURIComponent(cookiePair[1]);
}
}
// Return null if not found
return null;
}
var cart = JSON.parse(getCookie('cart'))
if (cart == undefined){
cart = {}
console.log('Cart Created!')
document.cookie ='cart=' + JSON.stringify(cart) + ";domain=;path=/"
}
console.log('Cart:', cart)
</script>
{% include 'main/includes/nav.html' %}
<section class="shop">
<div class="wrap">
{% for product in products %}
<div class="shop-card">
<a href="{{product.slug}}">
<div class="image-card-wrapper">
<img id="store-cart-img" src="{{ product.image_URL }}">
</div>
<div class="card-shop-info">
<p>{{product.name}}</p>
<p id="styleb">${{product.final_price | floatformat:2}} | <a data-product="{{product.id}}" data-action="add" class="add-to-cart-action update-cart">Add to cart</a></p>
</div>
</a>
</div>
{% endfor %}
</div>
</section>
<script type="text/javascript" src="{% static 'store/js/cart.js' %}"></script>
{% include 'main/includes/footer.html' %}
сделайте temporary_cart_section в вашем views.py и выведите содержимое внутри <section class="shop"> {# #} </section> (убедитесь, что вы не поставили тег section) с той же контекстной переменной, которую вы отправили туда, т.е. product
в вашем cart.js замените location.reload() на update_cart_section() и этот код (я предполагаю, что у вас установлен и импортирован jquery)
function update_cart_section(){
$.ajax({
url: '{# temporary-cart-section-url #}',
success: function (result) {
$('section .shop').html(result)
},
});
}