代码之家  ›  专栏  ›  技术社区  ›  Mohi

如果不刷新页面,Ajax将无法工作

  •  -2
  • Mohi  · 技术社区  · 1 年前

    Ajax在不刷新页面的情况下无法工作。我正在用django编写一个电子商务网站,需要显示购物车中的产品数量,但如果不刷新页面,它就不会显示数量。

            <script>
                $(document).on("click", "#add_button", function (e) {
                    e.preventDefault();
                    $.ajax({
                       type: "POST",
                       url: "{% url "add_cart" %}",
                       data: {
                         product_id: $("#add_button").val(),
                         csrfmiddlewaretoken: "{{ csrf_token }}",
                         action: "post",
                       },
                        success: function (json) {
                            {#console.log(json)#}
                            document.getElementById("cart_quantity").textContent = json.qty
                        },
                        error: function (xhr, errmsg, err) {
    
                        }
                    });
                    
                })
            </script>
    
    class Cart:
        def __init__(self, request):
            self.session = request.session
            cart = self.session.get("cart_key")
            if cart is None:
                cart = self.session["cart_key"] = {}
            self.cart = cart
    
        def add(self, product):
            product_id = str(product.id)
            if product_id in self.cart:
                pass
            else:
                self.cart[product_id] = {"Price: ": str(product.price)}
            self.session.modified = True
    
        def __len__(self):
            return len(self.cart)
    
    def add_cart(request):
        cart = Cart(request)
        if request.POST.get("action") == "post":
            product_id = int(request.POST.get("product_id"))
            product = get_object_or_404(Product, id=product_id)
            cart.add(product=product)
            cart_quantity = cart.__len__()
            # response = JsonResponse({"product name: ": product.name})
            response = JsonResponse({"qty: ": cart_quantity})
            return response
    
    <p id="cart_quantity" >{{ cart|length }}</p>
    

    当我添加产品时,我的购物按钮会显示这个,当我刷新时,会显示数量 enter image description here

    1 回复  |  直到 1 年前
        1
  •  0
  •   Eun ji Gater    1 年前

    我认为问题是由于Django视图中JSON响应中的键与ajax js试图在目标上访问的键不匹配造成的。(api…)。 为什么我这么认为: 您的代码:

    def add_cart(request):
     cart = Cart(request)
     if request.POST.get("action") == "post":
     product_id = int(request.POST.get("product_id"))
     product = get_object_or_404(Product, id=product_id)
     cart.add(product=product)
     cart_quantity = len(cart)
     response = JsonResponse({"qty:": cart_quantity}) # Key is "qty:"
     return response
    

    我看到JSON响应中的关键字是“ 数量: “而不是” 数量 “您正试图使用”访问您的json json.qty “根据此代码:

    success: function (json) {
     document.getElementById("cart_quantity").textContent = json.qty; // Trying to access "qty"
    }
    

    并且与您之前定义的“qty:”不同。换句话说:json中的qty与键“qty:”不匹配。(带结肠)。最后,你可能会从qty中得到“undefined”,因为你试图访问它,而不是正确的“qty:”(代码中正确且原始的键)。 如果你添加(查看错误) console.log(json); 之前

    document.getElementById(“cart_quantity”).textContent=json.qty;

    在这种功能中

    success: function (json) {
     console.log(json); // Log the JSON response
     document.getElementById("cart_quantity").textContent = json.qty;
    }
    

    你会看到的 { "qty:": 5 // The key includes a colon } 如果没有它,就不会按照你想要的那样。(没有结肠的数量)。

    解决方案是: 从数量中删除冒号。因为我之前解释过json中的不匹配。 这是正确的代码:

    def add_cart(request):
    cart = Cart(request)
    if request.POST.get("action") == "post":
    product_id = int(request.POST.get("product_id"))
    product = get_object_or_404(Product, id=product_id)
    cart.add(product=product)
    cart_quantity = len(cart)
    response = JsonResponse({"qty": cart_quantity}) # Key is "qty" without colon
    return response