简体   繁体   English

我想在不使用 AJAX 和 Django 刷新页面的情况下将产品添加到购物车中

[英]I want to add product in cart without refreshing page with AJAX and Django

Nothing will ne happened when I submit product in the the cart.当我在购物车中提交产品时,什么都不会发生。 I want to use AJAX without refreshing page.我想在不刷新页面的情况下使用 AJAX。 When I submit the console message will be displayed.当我提交控制台消息时将显示。 I'm trying to use AJAX first.我正在尝试首先使用 AJAX 。 Trying to add product in the cart without refreshing page.尝试在不刷新页面的情况下将产品添加到购物车中。 I need help please:)我需要帮助:)

Views Django视图 Django

def add_cart(request, product_id):
    cart = Cart(request)
    product = get_object_or_404(Product, id=product_id)

    form = CartProductForm(request.POST)
       
    if form.is_valid():
        cd = form.cleaned_data
        cart.add(product=product,
                quantity=cd['quantity'],
                update_quantity=cd['update_qt']
                )
                
    return JsonResponse({'status': 'success'}) 

Form形式

from django import forms
from django.core.validators import MinValueValidator, MaxValueValidator

class CartProductForm(forms.Form):
    quantity = forms.IntegerField(initial=1)
    update_qt = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput)

HTML Code HTML 代码

<form action="{% url "..." %}"  method="post" data-id="{{ ... }}" class="form-order" id="form">
    {{ cart_product_form }}
    {% csrf_token %}
    <a data-id="{{ ... }}" class="buy-product"><button>BUY</button></a>
</form>

JS Code JS代码

        $(".buy-product").on('click', function(e){
            e.preventDefault();
            var product_id = $(this).attr('data-id')
            var quantity = 1
            console.log(product_id)
            console.log(quantity)

            data = {
                'product_id': product_id,
                'quantity': quantity
            }
            var point='/cart/add/'+product_id+'/'
            
            $.ajax({
                headers:{
                'Content-Type':'application/json',
                'X-CSRFToken':csrftoken,
                },
                url: point,
                type: 'POST',


                data: data,

                success: function(data){
                    console.log('success')
                    console.log(csrftoken)
                    
                }
        })
    })


You need to add csrftoken in data: {csrfmiddlewaretoken':csrftoken} .您需要在 data: {csrfmiddlewaretoken':csrftoken}中添加 csrftoken 。 Also I don't see when you initialize your variables, but I think is just example.我也看不到你什么时候初始化你的变量,但我认为这只是一个例子。 Check this answer for more: link检查此答案以获取更多信息:链接

You can prevent form from refreshig the page and then do whatever you need with your JS code:您可以阻止表单刷新页面,然后使用 JS 代码执行您需要的任何操作:

<form action="{% url "..." %}"  method="post" data-id="{{ ... }}" class="form-order" id="form" onsubmit="myFunction(event)">
...
</form>
<script>
function myFunction(event){
    event.preventDefault();
}
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM