繁体   English   中英

使用带有Django,Ajax和Jquery的复选框,一次将一项添加到“购物车”中

[英]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-cartdjango-carton 还有Django电子商务软件包的比较表 希望你能走。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM