Javascript 将项目一次添加一个到“中”;购物车;在Django、Ajax和Jquery中使用复选框
新代码现在包括在内,但仍然不起作用 我正在尝试使用复选框选择一个项目并将其添加到页面顶部的“购物车”中。页面上的每个项目旁边都有一个复选框,选中该复选框后,应将项目添加到购物车,并在页面顶部的“购物车”部分显示该项目名称。因此,当用户进入页面并检查一个项目时,我希望该项目名称出现在页面顶部的“购物车”部分 (即,选中一个项目,项目名称显示在页面顶部;选中另一个项目,项目名称显示在页面顶部第一个项目旁边;等等) 使用以前版本的代码,我已经能够获得页面上列出的第一个项目(并且只有第一个项目)以实际显示在“购物车”部分。我已经尝试了我能做的一切,但我对Django、Ajax和Jquery是完全陌生的。有人能帮忙吗!?谢谢大家! list.html的“购物车”部分:Javascript 将项目一次添加一个到“中”;购物车;在Django、Ajax和Jquery中使用复选框,javascript,jquery,ajax,django,Javascript,Jquery,Ajax,Django,新代码现在包括在内,但仍然不起作用 我正在尝试使用复选框选择一个项目并将其添加到页面顶部的“购物车”中。页面上的每个项目旁边都有一个复选框,选中该复选框后,应将项目添加到购物车,并在页面顶部的“购物车”部分显示该项目名称。因此,当用户进入页面并检查一个项目时,我希望该项目名称出现在页面顶部的“购物车”部分 (即,选中一个项目,项目名称显示在页面顶部;选中另一个项目,项目名称显示在页面顶部第一个项目旁边;等等) 使用以前版本的代码,我已经能够获得页面上列出的第一个项目(并且只有第一个项目)以实际显
<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>
这个问题相当广泛,很可能会被关闭或被否决而不存在,但我想我会尝试引导你朝着正确的方向前进 视图函数远远不能返回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')
这里需要记住的重要一点是,要放入会话中的任何内容都必须可以序列化为字符串。该模块非常适合将复杂的Python对象编码/解码为JSON
将关注点分开,您可能希望将从响应返回的数据传递给JavaScript模板函数,如s\uu0.template()
,并将响应中的数据传递给它,而不是从视图返回HTML
还有为Django:and准备的手推车。还有这个Django电子商务包。希望这能让你走。非常感谢!我真的很感激你的建议。我已经为此工作了好几天了,所以任何至少能为我指明正确方向的东西都是很好的。不客气。我知道当你知道自己想做什么,但同时又在学习一个新的框架时,会有多沮丧。如果你需要额外的帮助,请告诉我。嗨,布兰登-我试着尽可能长时间地坚持,但仍然无法让它工作…我发布了我的新代码。有没有哪一个地方我出了问题?我正在试验一个JavaScript模板函数,就像你提到的一样,但还没有成功。非常感谢。你好,斯蒂芬。我将尽可能快地为您介绍一下。我可以用一个示例应用程序来演示这一点,因为这里有一些问题需要解决,我可以稍后再回来补充回答。稍后,我会在这里向您发送一个可下载示例应用程序的链接。
$('#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);
};
});
});
});
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')
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')