以前用的Ajax实例,以后用的时候可以仿照写
JS部分
/* 下订单触发click事件,用来校验订单是否下成功,根据AJAX返回值展示不同页面*/
$('#order_btn').click(function(){
orderid = []
$('.goods_list_td').each(function(){
orderid.push($(this).attr('id'));
});
localStorage.setItem('order_finish',2);
$.post({
url:'/order/addorder/',
dataType:'json',
type:'POST',
data:{
'csrfmiddlewaretoken': '{{ csrf_token }}',
id:orderid,
total:totalPay,
address:$('#oaddress').text(),
},
})
.done(function(data){
if(data.status == 1){
$('.popup_con p').text('订单提交成功!');
$('.popup_con').fadeIn('fast', function() {
setTimeout(function(){
$('.popup_con').fadeOut('fast',function(){
window.location.href = '/user/user_center_order&1/';
});
},3000)
});
}
else if(data.status == 2){
$('.popup_con p').text('超出库存请修改!');
$('.popup_con').fadeIn('fast', function() {
setTimeout(function(){
$('.popup_con').fadeOut('fast',function(){
window.location.href = '/cart/';
});
},3000)
});
}
});
});
Python代码
def addorder(request):
"""
下订单功能
1)根据页面上AJAX传来的请求,依次将价格、地址、用户id、时间保存为一条订单数据,订单id由时间构建
2)由order函数传的orderlist,由place_order.html页面的JS构造成数组传到本视图,重新getlist解析为列表
作为订单详情页中购物车中的每个商品
3)根据步骤2)中得到的详细商品列表,构造订单详细信息表,减去相应的库存数量
4)步骤3)执行后删除购物车中的信息
"""
# 设置事务点,发生异常后回滚到此处
tran_id = transaction.savepoint()
# 根据POST和session获取信息
post = request.POST
orderlist = post.getlist('id[]')
total = post.get('total')
address = post.get('address')
uid = request.session.get('userid')
time = datetime.now()
# 创建订单表
order = OrderInfo()
order.oid = '%s%d' % (time.strftime('%Y%m%d%H%M%S'), uid)
order.user_id = uid
order.odate = time
order.ototal = Decimal(total)
order.oaddress = address
order.save()
# 遍历购物车中提交信息,创建订单详情表
for orderid in orderlist:
cartinfo = CartInfo.objects.get(id=orderid)
good = GoodsInfo.objects.get(cartinfo__id=cartinfo.id)
# 判断库存是否够
if int(good.gkucun) >= int(cartinfo.count):
# 库存够,移除购买数量并保存
good.gkucun -= int(cartinfo.count)
good.save()
goodinfo = GoodsInfo.objects.get(cartinfo__id=orderid)
# 创建订单详情表
detailinfo = OrderDetailInfo()
detailinfo.goods_id = int(goodinfo.id)
detailinfo.order_id = int(order.oid)
detailinfo.price = Decimal(int(goodinfo.gprice))
detailinfo.count = int(cartinfo.count)
detailinfo.save()
# 循环删除购物车对象
cartinfo.delete()
else:
# 库存不够出发事务回滚
transaction.savepoint_rollback(tran_id)
# 返回json供前台提示失败
return JsonResponse({'status': 2})
# 返回json供前台提示成功
return JsonResponse({'status': 1})