jquery - 如何在不刷新页面的情况下使用 jquery 将 django 视图中的数据动态加载到 django 模板?
问题描述
我正在尝试将 django 视图中的数据加载到我的 django 模板中,而无需使用 jquery 刷新页面。我的视图中有一个购物车功能,它返回用户购物车中的所有物品。我想使用 jQuery 在 django 模板中单击一个按钮来显示所有项目。我似乎无法弄清楚我做错了什么。
以下是我的看法:
def cart(request):
template = loader.get_template("main/cart.html")
if request.user.is_authenticated:
email = request.user.email
usercartitems = request.user.cart_item_set.all()
cartitems = []
store = ""
totalprice = 0
numberofitemsincart = len(cartitems)
for item in usercartitems:
quantity = item.product_quantity
store_id = item.store_id
product_id = item.product_id
storedetail = Store_detail.objects.get(pk = store_id)
product = Product.objects.get(pk = product_id)
item = {"quantity":quantity, "product":product}
cartitems.extend([item])
store = storedetail
numberofitemsincart = len(cartitems)
product = Product.objects.get(pk = product_id)
totalproductprice = product.price * int(quantity)
totalprice += totalproductprice
context={
'store':store,
'email':email,
'cartitems':cartitems,
'numberofitemsincart':numberofitemsincart,
'totalprice':totalprice,
}
return HttpResponse(template.render(context,request))
elif request.user.is_authenticated is False:
if request.session.get('cart'):
allitems = request.session['cart']
cartitems = []
totalprice = 0
for item in allitems.values():
store_id = item['store_id']
quantity = item['quantity']
product_id = item['product_id']
product = Product.objects.get(pk = product_id)
store = Store_detail.objects.get(pk = store_id)
totalproductprice = product.price * int(quantity)
totalprice += totalproductprice
cartdict = {'store':store,'product':product,'quantity':quantity,}
cartitems.append(cartdict)
context = {
'cartitems':cartitems,
'totalprice':totalprice,
}
else:
context = {}
return HttpResponse(template.render(context,request))
else:
return HttpResponse(template.render(context,request))
这是我的 jQuery:
$('#cart').click(
function(e){
e.preventDefault();
$.ajax({
type:"GET",
dataType: "json",
url:"{% url 'main:cart' %}",
data: {
'cartitems': cartitems
}
success:function(data){
console.log(data);
}
});
});
解决方案
看起来您希望根据json
您的请求处理数据。如果您的 html 页面中只有一项需要更新,对我来说,没有必要渲染整个内容,这jquery
是一种方法。
我还认为为此处理上下文内容太复杂了。这是一个返回用户json
响应的示例,然后您可以在您jquery
的代码中使用:
from django.http import JsonResponse
def cart(request):
try:
[...] # your stuff
# define here the json data you want to return, in a list
your_json_data = [{
'key1': val1,
'key2': val2,
...
}]
return JsonResponse(your_json_data, safe=False)
except Exception as e:
return JsonResponse({})
然后,您将能够使用刚刚获取的数据!