简体   繁体   中英

Django return JsonResponse and catch data in ajax request

Here is my view. I am returning JsonResponse to ajax request where catching incoming data from my view 'line_product_total': total, and other contexts

    def get(self, request, *args, **kwargs):
    cart = self.get_object()
    product_id = request.GET.get('product')
    delete_product = request.GET.get('delete', False)
    product_added = False

    if product_id:
        product_instance = get_object_or_404(Product, id=product_id)
        amount = request.GET.get('amount', 1)
        try:
            if int(amount) < 1:
                delete_product = True
                return HttpResponse('IntegrityError', delete_product)
        except:
            raise Http404

        cart_product, created = CartProduct.objects.get_or_create(cart=cart, product=product_instance)
        if created:
            product_added = True
        if delete_product:
            cart_product.delete()
        else:
            cart_product.amount = amount
            cart_product.save()
        if not request.is_ajax():
            return HttpResponseRedirect(reverse('e_commerce:cart'))
            # return cart_product.cart.get_absolute_url
    if request.is_ajax():
        try:
            total = cart_product.line_product_total
        except:
            total = None
        data = \
            {
                'deleted': delete_product,
                'product_added': product_added,
                'line_product_total': total,

             }
        return JsonResponse(data)

    cart = Cart.objects.get(pk=cart.pk)
    return render(request, 'sales/cart.html', {'cart': cart})

js

     $('.type_number').change(function () {

    var product = $(this).next('input[type=hidden]').val();
    var amount = $(this).val();
    var data = {
        product:product,
        amount: amount
    };
    console.log(data);
    $.ajax({
        type: 'GET',
        url: '{% url "e_commerce:cart" %}',
        data: data,
        success: function (data) {
            $('#jquery-message').text('Added' + data.product_added + 'Deleted' + data.deleted);
            if (data.deleted) {
                $('#product-'+product).fadeOut;
            }
            else {
                $('#product-line-total-'+product).text(data.line_product_total);
            }
        },
        error: function(response, error) {
            $('#add-form').submit()
        }
    })
 })

template

<form action="." method="GET">


 <h4 id="product-line-total-{{ product.id }}">{{ product.line_product_total }}</h4>

<input class="type_number" style="text-align: center;margin-left: -50px;" title="" type="number" name="amount" value="{{ product.amount }}">
        <input type="hidden" name="product" value="{{ product.product.id }}">
        <button type="submit"></button>
</form>

In short i can not catch variable line_product_total in my ajax It just saying Unresolved variable line_product_total

But i am sending this variable. What problem? Guys at least tell me what the problem itself can not do in any way

Thank you in advance :)

Your view code doesn't always return a JsonResponse. You should trace both the view execution (adding some print or - better - logging.debug() before each return statement) and also log the effective response you get on the client side instead of blindly assuming you do have a json response with a 200 status.

Also your code is really really bad and even dangereous.

First and most, a GET request MUST be idempotent (it must NOT change the server's state). Using GET for a requests that creates / updates / delete objects from your database is really looking for trouble.

Then you exception handlers are more than useless, they are harmfull. They catch just any exception (including a SystemExit !) and silently ignore them, so you will never know when, what, how and why anything goes wrong. Keep your try blocks as short as possible (one single statement if possible), only catch exceptions you expect and know how to handle, log whatever you catch (with as much contextual infos as you can), and if you really don't know what do with an exception just let it propagate. The user will get a 500 error (yes, shit happens), and (assuming your server and project are correctly configured) you will get a nice error email with the full traceback etc, so you know something went wrong and have a chance to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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