Как сделать добавление в корзину без перезагрузки страницы (js и django)?

Я делаю функциональность добавления в корзину, и я хочу показать новую сумму корзины после добавления в корзину без перезагрузки страницы. Сейчас мне приходится перезагружать страницу, чтобы показать изменения в корзине после добавления товара.

(ЧАСТЬ КОДА МОЖЕТ БЫТЬ НА ДАТСКОМ, НАДЕЮСЬ ЭТО НОРМАЛЬНО)

HTML (Кнопка добавления в корзину)

<div class="buy-item flex flex-ai-c">
            <button data-product="{{product.id}}" data-action="add" class="add-button add-btn update-cart">TILFØJ TIL KURV</button>
            <div class="flex flex-ai-c flex-jc-c">
                <span class="cart-quantity-text">ANTAL</span>
                <input class="cart-quantity-input" type="number" value="1">
            </div>
        </div>

JS

function addCookieItem(productId, action) {

if(action == 'add'){
    if(cart[productId] == undefined){
        cart[productId] = {'quantity':parseInt(antal.value)}
    }else{
        cart[productId]['quantity'] += parseInt(antal.value)
    }
}

if(action == 'add-from-cart'){
        cart[productId]['quantity'] += 1
}

if(action == 'remove-from-cart'){
    cart[productId]['quantity'] -= 1

    if(cart[productId]['quantity'] <= 0){
        console.log('Remove Item')
        delete cart[productId]
    }
}

if(action == 'delete'){
    delete cart[productId]
}
console.log('Cart:', cart)
document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
location.reload()
}

Django

def cookieCart(request):

try:
    cart = json.loads(request.COOKIES['cart'])
except:
    cart = {}

print('Cart:', cart)
items = []
order = {'get_cart_total':0, 'get_cart_items':0}
cartItems = order['get_cart_items']

for i in cart:
    try:
        cartItems += cart[i]['quantity']

        product = Product.objects.get(id=i)
        total = (product.price * cart[i]['quantity'])

        order['get_cart_total'] += total
        order['get_cart_items'] += cart[i]['quantity']

        item = {
            'product':{
                'id':product.id,
                'name':product.name,
                'price':product.price,
                'imageURL': product.imageURL,
                'stripe-price': product.stripe_price_id,
                'description': product.description,
                'vare_nr': product.vare_nr,
            },
            'quantity': cart[i]['quantity'],
            'get_total': total
        }
        items.append(item)

    except:
        pass
return {'cartItems': cartItems, 'order': order, 'items':items}

def cartData(request):

cookieData = cookieCart(request)
cartItems = cookieData['cartItems']
order = cookieData['order']
items = cookieData['items']


return {'cartItems': cartItems, 'order': order, 'items':items}

Вы можете решить ее с помощью (очень) разных подходов:

  1. использование старого способа fashine - вызов jQuery Ajax
  2. .
  3. использование HTMX - довольно новый и менее традиционный способ увеличить возможности шаблонизации без написания JS кода.
  4. использование JS Frontend фреймворка/библиотеки (React, Vue, Angular, Svelte и т.д.)
  5. .

есть, конечно, и другие методы, но я думаю, что для Django эти будут основными и наиболее документированными решениями.

Вернуться на верх