Ajax не работает без обновления страницыJquery

Программирование на jquery
Ответить
Anonymous
 Ajax не работает без обновления страницы

Сообщение Anonymous »

Ajax не работает без обновления страницы. Я пишу код веб-сайта электронной коммерции в django, и мне нужно показать количество продуктов в корзине, но он не показывает количество без обновления страницы.

Код: Выделить всё

        
$(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) {

}
});

})

Код: Выделить всё

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

Код: Выделить всё

{{ cart|length }}
Моя кнопка покупок показывает это, когда я добавляю товар, а когда я обновляю, показывает количество
введите здесь описание изображения

Подробнее здесь: https://stackoverflow.com/questions/787 ... g-the-page
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Jquery»