递增和递减按钮不工作

2024-09-27 02:21:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用django和javascript构建一个购物车,为此我添加了两个按钮来增加和减少购物车项目,但它不起作用。我不适合使用javascript,因为我遵循了教程。我也这么做了,但仍然不起作用

这是my cart.html:

{% load static%}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="stylesheet" href="{% static 'css/cart.css' %}" type="text/css" />
    <link
      href="https://fonts.googleapis.com/css2?family=Roboto+Slab&display=swap"
      rel="stylesheet"
    />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>GnG</title>
    <script type="text/javascript">
      var user = "{{user.username}}";

      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");
    </script>
    <script src="{% static 'js/cart.js' %}"></script>
  </head>
  <body>
    <!--cart start-->

    <div class="table">
      <div class="layout-inline row th">
        <div class="col col-pro">Product</div>
        <div class="col col-price align-center">Price</div>
        <div class="col col-qty align-center">QTY</div>
        <div class="col">DELIVERY CHARGE</div>
        <div class="col">Total</div>
      </div>
      {% for item in items %}
      <div class="layout-inline row">
        <div class="col col-pro layout-inline">
          <img
            src="{{item.product.product_image.url}}"
            height="60px,"
            width="50px"
          />
          <p>{{item.product.product_name}}</p>
        </div>

        <div class="col col-price col-numeric align-center">
          <!-- <p>{{item.product_total}}</p> -->
          <p>৳{{item.product.product_price}}</p>
        </div>

        <div class="col col-qty layout-inline">
          <!-- <input type="numeric" value="{{item.quantity}}"/> -->
          <input
            class="update-cart"
            type="submit"
            value=" + "
            data-product="{{item.product.product_id}}"
            data-action="add"
          />
          <p class="quantity">{{item.quantity}}</p>
          <input
            class="update-cart"
            type="submit"
            value=" - "
            data-product="{{item.product.product_id}}"
            data-action="remove"
          />
        </div>

        <div class="col col-vat col-numeric">
          <p>N/A</p>
        </div>
        <div class="col col-total col-numeric">
          <p>৳{{item.product_total}}</p>
        </div>
      </div>
      {% endfor %}

      <div class="layout-inline row">
        <div class="total__item">
          <p>Total Item: {{order.get_cart_items}}</p>
          <p>Cart Total: ৳{{order.get_cart_total}}</p>
        </div>
      </div>
    </div>

    <a href="{% url 'checkout' %}" class="btn btn-update">Checkout</a>
  </body>
</html>

这是我的cart.js:

var updateBtn = document.getElementsByClassName('update-cart')

    for(var i = 0; i < updateBtn.length; i++){
        updateBtn[i].addEventListener('click', function(){
            var productId = this.dataset.product
            var action = this.dataset.action
            console.log('productId:',productId, 'action:',action)

            console.log('USER:',user)
            if(user === 'AnonymousUser'){
                console.log('Please Login to Order!')
            }
            else {
                updateUserOrder(productId, action)
            }
        })
    }

    function updateUserOrder(productId, action){
        console.log('Product added to cart!')

        var url = '/update_item/'

        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken
            },

            body: JSON.stringify({'productId': productId, 'action':action})
        })

        .then((response) => {
            return response.json()
        })

        .then((data) => {
            console.log('data:',data)
            location.reload()
        })

    }

以下是我的视图.py:

def updateCart(request):
    data = json.loads(request.body)
    productId = data['productId']
    action = data['action']

    print('action:', action)
    print('productId:', productId)

    customer = request.user.customer_name
    product = ProductModel.objects.get(product_id=productId)
    order, created = OrderModel.objects.get_or_create(
        customer=customer, complete=False)

    orderItem, created = OrderItem.objects.get_or_create(
        order=order, product=product)

    if action == 'add' or action == 'remove':
        if action == 'add':
            orderItem.quantity = (orderItem.quantity + 1)
        elif action == 'remove':
            orderItem.quantity = (orderItem.quantity - 1)

        orderItem.save()

    if orderItem.quantity <= 0:
        orderItem.delete()
    return JsonResponse('Item added to cart', safe=False)

Tags: namedivdataifcookievaractioncol

热门问题