一次添加一个项目到“;推车”;在Django、Ajax和Jquery中使用复选框

Add items one at a time to a "cart" using checkboxes with Django, Ajax, and Jquery

本文关键字:Ajax Django Jquery 复选框 添加 一次 一个 项目 推车      更新时间:2023-09-26

现在包含了新代码,但仍然无法工作。。。

我正在尝试使用复选框来选择一个项目,并将其添加到页面顶部的"购物车"中。页面上的每个项目旁边都有一个复选框,选中该复选框后,应将该项目添加到购物车中,并在页面顶部的"购物车"部分显示该项目名称。因此,当用户进入页面并检查项目时,我希望该项目名称显示在页面顶部的"购物车"部分。

(即,选中一个项目,项目名称出现在页面顶部;选中另一个项目时,项目名称显示在页面顶部的第一个项目旁边;等等)

使用以前版本的代码,我已经能够获得页面上列出的第一个项目(并且只有第一个项目),以实际显示在"购物车"部分。我已经尝试了我所能尝试的一切,但我对Django、Ajax和Jquery完全陌生。有人能帮忙吗!?非常感谢。

list.html的"cart"部分:

    <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);
            };
        });
    });
});

项目视图.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模板函数,如Underscore的_.template(),并将响应中的数据传递到它,而不是从视图中返回HTML。

Django也有预制推车:Django推车和Django纸箱。还有这张Django电子商务软件包的对比图。希望这能让你继续前进。