[英]Add items one at a time to a “cart” using checkboxes with Django, Ajax, and Jquery
現在已包含新代碼,但仍然無法使用...
我正在嘗試使用復選框來選擇一個項目,然后將其添加到頁面頂部的“購物車”中。 頁面上的每個項目旁邊都有一個復選框,選中該復選框后,應將其添加到購物車中,並在頁面頂部的“購物車”部分中顯示該項目名稱。 因此,當用戶瀏覽頁面並檢查項目時,我希望該項目名稱出現在頁面頂部的“購物車”部分中。
(即檢查一個項目,項目名稱顯示在頁面頂部;檢查另一個項目,該項目名稱顯示在頁面頂部的第一個項目旁邊;等等。)
使用我的代碼的早期版本,我已經能夠獲取頁面上列出的第一項(只有第一項),以實際顯示在“購物車”部分中。 我已經盡力了,但是我對Django,Ajax和Jquery完全陌生。 有人可以幫忙嗎? 謝謝!
list.html的“購物車”部分:
<div id="programCart">
<table cellpadding="5" cellpadding ="2" border="2" id="selected_programs_cart">
<tbody>
<tr>
<td id="selectionsHere"> SampleSelection1 </td>
</tr>
</tbody>
</table>
</div>
列出項目的html,在list.html的每個部分旁邊都有一個復選框(這些項目顯示為較大的“ for”循環):
<td>
<form id="programs-selected" method="GET" action="select_citations">
<script type="text/javascript" src="/static/js/citations.js"></script>
<ul>
<li><input type="checkbox" id="programCheckbox" name="programs_to_add" value="{{software.id}}" />
</li>
</ul>
</td>
</form>
selectitems.js:
$('#programCheckbox').click(function(){
var softwareID
softwareID = $(this).attr("value")
$.get('add_to_cart', function(data){
$tbody = $("selected_programs_cart").find('tbody');
$.each(data, function(){
var displayCart = json.addingToCart;
for (var key in displayCart)
if (key == 'cart'){
var value = displayCart[key];
for (var softwareName in value)
$("<td>" + softwareName + "<td>").appendTo($tbody);
};
});
});
});
itemview.py
def add_to_cart(request):
#dict of 'cart' to list of selected programs to return
to_JSON = {}
#Programs are already in the cart and the "cart" key already exists in the session-
if 'cart' in request.session:
logger.warning("cart found")
software_id = request.GET.get('softwareID')
softwareObject = Software.objects.get(pk='software_id')
softwareName = softwareObject.title
addingToCart = request.session.get('cart')
request.session['addingToCart'].append(softwareName)
to_JSON = request.session['addingToCart']
#first time clicking on a program, no existing cart in session: the session should store 'cart' as the key and a list of selected programs as the value
else:
logger.warning("cart not found")
#get the softwareID of the most recently clicked program
software_id = request.GET.get('softwareID')
if software_id == None:
#oops, can't retrieve this from the request
logger.warning("cannot find software_id in the request")
return HttpResponse(request) # TODO: there's probably a better way to handle this
else:
logger.warning( "request.GET.get('softwareID'): {}".format(request.GET.get('softwareID')) )
try:
softwareObject = Software.objects.get(pk='software_id')
except Software.DoesNotExist as e:
logger.warning("oh oh, Someone is trying to access a Software ID that doesn't exist: {}".format(e))
# TODO: what to do if this happens?
except ValueError as e:
logger.warning("oh dear: {}".format(e) )
#TODO: if an exception happens, the softwareObject won't exist, what should happen then?
softwareName = softwareObject.title
#create an entry in the session dictionary for the cart and program list
request.session['cart'] = []
#add the first selected program to the list
request.session['cart'].append(softwareName)
addingToCart = request.session['cart']
to_JSON = request.session['addingToCart']
response_data = json.dumps(to_JSON)
return HttpResponse(response_data, content_type='application/json')
#return HttpResponse(json.dumps(cart, ensure_ascii=False), content_type='application/json')
這個問題相當廣泛,很可能會被關閉或被淘汰,但是我想我會盡力引導您朝着正確的方向發展。
您的視圖函數遠不能返回jQuery方法可以使用並用於更新DOM的JSON。 這是一些偽代碼:
import json
from django.http import HttpResponse
# or if you're using Django 1.7, you can use the JsonResponse class:
# https://docs.djangoproject.com/en/1.7/ref/request-response/#jsonresponse-objects
from your_app.models import Software
def add_to_cart(request):
# get an existing cart from the request
cart = request.session.get('cart', {'items': []})
# get the objects for the ids in the request
software_ids = request.GET.getlist('software_ids')
software = Software.objects.filter(id__in=software_ids)
# append the items to the cart
cart['items'].append(software)
# set the cart into session so you can persist it across requests
request.session['cart'] = cart
# dump the cart to JSON and send back a the response
return HttpResponse(json.dumps(cart, ensure_ascii=False),
content_type='application/json')
這里要記住的重要一點是,要放入會話中的任何內容都必須可序列化為字符串。 jsonpickle模塊非常適合將復雜的Python對象編碼/解碼為JSON。
保持關注分開,你可能想通過從響應返回給一個JavaScript模板功能,如數據下划線的_.template()
和響應傳遞給它的數據,而不是從視圖返回HTML。
還有針對Django的預制購物車 : django-cart和django-carton 。 還有Django電子商務軟件包的比較表 。 希望你能走。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.