如何在ajax发布后呈现模板?

时间:2016-01-18 11:41:00

标签: jquery ajax django

我正在尝试使用ajax发布表单,然后使用它呈现模板,但它返回第一个HttpResponse。

这是Post方法

def post(self , request , *args , **kwargs):
        context = {}
        self.object = self.get_object()
        user_checkout_id = request.session.get('user_checkout_id')
        user_checkout = UserCheckout.objects.get(id=user_checkout_id)
        nonce = request.POST.get("payment_method_nonce")


        if request.POST.get('action') == 'guest':
            email = request.POST.get('email')
            user_checkout , created = UserCheckout.objects.get_or_create(email=email)

            if created:
                self.request.session['user_checkout_id'] = user_checkout.id
                user_checkout.save()

            return HttpResponse(json.dumps({'status' : 'True'}))


        if request.POST.get('action') == 'order':
            name = request.POST.get('name')
            address = request.POST.get('address')
            pincode = request.POST.get('pincode')
            mobile = request.POST.get('mobile')
            alternate = request.POST.get('alternate')

            address , created = UserAddress.objects.create(user = user_checkout , name=name , address=address , pincode=pincode ,  mobile_number=mobile , alternate_number=alternate)


            if created:
                self.request.session["address_id"] = address.id

            html = render_to_string('orders/new_order.html', {'order': self.get_order()})

            return HttpResponse(html)


        if nonce:
            result = braintree.Transaction.sale({
                "amount" : order_total ,
                "payment_method_nonce" : nonce ,
                "options":{
                "submit_for_settlement": True
                }

                })
            if result.is_success:
                order.mark_completed(order_id = result.transaction.id) 

            return HttpResponseRedirect(reverse('orders'))  

        else:
            HttpResponseBadRequest("error")

以下是使用ajax

发布数据的脚本
<script type="text/javascript">
function getOrder() {
        $("#loading-image").show();
        name = $("#name").val();
        address = $("#addrs").val();
        pincode = $("#pincode").val();
        mobile = $("#mobile").val();
        alternate = $("#alternate").val();
        console.log(name + address + pincode + mobile + alternate);
        $.ajax({        
            type: "POST",
            data : { action : 'order' , csrfmiddlewaretoken: '{{ csrf_token }}' , name:name , address:address , pincode:pincode , mobile:mobile , alternate:alternate },
            url: "{% url 'checkout' %}",
            success: function(data) {
              alert(data);
            },
            error: function(response, error) {
                alert(error);  
            }
        });
    }
</script>

可能是什么问题......需要帮助

编辑 其他包含在HttpBadRequest

0 个答案:

没有答案