我有一个购物车,我可以在其中添加或删除物品。我正在使用购物车会话和 AJAX 来添加/删除产品,而无需刷新页面。当购物车中的一项商品时,它可以正常工作,但它仅在新页面上显示请求状态,如果我想查看更改,我需要刷新它。当购物车中只有一种产品时,它工作正常,否则我需要刷新页面。
购物车.html
<div class="quantity__row">
<form action="{% url 'remove_cart' %}" method="post" id="removeCartID">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="hidden" name="product_id" value="{{ item.product.id }}" id="productRemoveID">
<input type="submit" value="-" class="quantity__number-minus">
</form>
<input type="number" min="1" value={{ item.quantity }} readonly="readonly" class="quantity__input" id="quantityID"/>
<form action="{% url 'add_cart' %}" method="post" id="addCartID">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="hidden" name="product_id" value="{{ item.product.id }}" id="productAddCartID">
<input type="submit" value="+" class="quantity__number-plus">
</form>
</div>
views.py
def add_to_cart(request):
if request.method == 'POST':
product_id = request.POST.get('product_id')
product = Product.objects.get(id=int(product_id)-1)
cart = Cart(request)
cart.add(product=product)
cart_quantity = cart.get_total_len()
return JsonResponse({'success': True, 'cart_quantity': cart_quantity})
def cart_remove(request):
if request.method == 'POST':
product_id = request.POST.get('product_id')
product = Product.objects.get(id=int(product_id))
cart = Cart(request)
cart.remove(product)
cart_quantity = cart.get_total_len()
return JsonResponse({'success': True, 'cart_quantity': cart_quantity})
脚本.js
$(function() {
$('#addCartID').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '{% url "add_cart" %}',
type: 'post',
data: {
product_id: $('#productAddCartID').val(),
product_quantity: $('#quantityID').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function (response) {
if (response.success) {
$('#quantityID').val(response.cart_quantity);
$('#modal__content').html('<p>Товар добавлен в корзину</p>').show();
} else {
console.log(response);
}
}
});
});
});
$(function() {
$('#removeCartID').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '{% url "remove_cart" %}',
type: 'post',
data: {
product_id: $('#productRemoveID').val(),
product_quantity: $('#quantityID').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function (response) {
if (response.success) {
$('#quantityID').val(response.cart_quantity);
$('#modal__content').html('<p>Товар убран из корзины!</p>').show();
} else {
$('#modal__content').html('<p>' + response + '</p>').show();
}
}
});
});
});
终于找到解决办法了。这个想法是接收元素的唯一 ID 并获得确切的形式,即
event
发生的地方。我添加了 $(this)
并且我得到了唯一的 ID。我还需要添加一个检查:
ajax.js
$(function() {
$('.addCartClass').on('submit', function(e){
e.preventDefault();
let product_id = $(this).find('[name="product_id"]').attr('id').split('_')[1];
$.ajax({
url: '/add-certain-amount/',
type: 'post',
data: {
product_id: product_id,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function (response) {
if (response.success) {
let value = $('#quantityID_' + product_id).text();
$('#quantityID_' + product_id).text(Number(value) + 1);
let amount = $('#productAmount_' + product_id).text().split(' ')[0];
$('#productAmount_' + product_id).text(Number(amount) + 1 + ' шт.');
} else {
console.log(response);
}
}
});
});
});
$(function() {
$('.removeCartClass').on('submit', function(e){
e.preventDefault();
let product_id = $(this).find('[name="product_id"]').attr('id').split('_')[1];
$.ajax({
url: '/remove/',
type: 'post',
data: {
product_id: product_id,
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function (response) {
if (response.success) {
let value = $('#quantityID_' + product_id).text();
$('#quantityID_' + product_id).text(Number(value) - 1);
let amount = $('#productAmount_' + product_id).text().split(' ')[0];
$('#productAmount_' + product_id).text(Number(amount) - 1 + ' шт.');
} else {
console.log(response);
}
}
});
});
});
views.py
def add_certain_amount(request):
if request.method == 'POST':
product_id = request.POST.get('product_id')
product = Product.objects.get(id=product_id)
cart = Cart(request)
cart.add(product=product)
cart_quantity = cart.get_total_len()
return JsonResponse({'success': True, 'cart_quantity': cart_quantity})
def cart_remove(request):
if request.method == 'POST':
product_id = request.POST.get('product_id')
product = Product.objects.get(id=int(product_id))
cart = Cart(request)
cart.remove(product)
cart_quantity = cart.get_total_len()
return JsonResponse({'success': True, 'cart_quantity': cart_quantity})
base.html
<div class="quantity__row">
<form action="{% url 'remove_cart' %}" method="post" class="removeCartClass">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="hidden" name="product_id" value="{{ item.product.id }}" id="remove_{{item.product.id}}">
<input type="submit" value="-" class="quantity__number-minus">
</form>
<span class="quantity__input" id="quantityID_{{item.product.id}}">{{ item.quantity }}</span>
<form action="{% url 'add_certain' %}" method="post" class="addCartClass">
{% csrf_token %}
{{ item.update_quantity_form.quantity }}
{{ item.update_quantity_form.update }}
<input type="hidden" name="product_id" value="{{ item.product.id }}" id="add_{{item.product.id}}">
<input type="submit" value="+" class="quantity__number-plus">
</form>
</div>