Ajax 请求在 django 中无法正常工作 [英] Ajax request not working properly in django

查看:26
本文介绍了Ajax 请求在 django 中无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ajax请求的JS代码

views.py 中的 updateapi:

def update_util(request):pk = int(request.POST.get('item_id'))rest_id = request.session['rest_id']餐厅 = Restaurant.objects.get(pk = rest_id)cart_obj = Cart.objects.new_or_create(request)remove = request.POST.get('remove')item = FoodItem.objects.get(pk=pk)# 打印(PK)如果删除 == '1':购物车obj.items.remove(item)别的:购物车obj.items.add(item)定义更新(请求):update_util(请求)rest_id = request.session['rest_id']返回重定向(反向('餐厅:菜单',kwargs = {'pk':rest_id}))def updateapi(请求):如果 request.is_ajax():update_util(请求)cart_obj = Cart.objects.new_or_create(request)打印(request.POST.get('remove'),'调用')项目 = []数据 = {}对于cart_obj.items.all() 中的项目:items.append({'name':item.name, 'price':item.price,'id':item.id})data_ = {'items':items , 'total':cart_obj.total ,'小计':cart_obj.subtotal}返回 JsonResponse(data_)

正在调用删除的 HTML 表单:

<头><第>项目</th><th>价格</th><th></th></thead><tbody class="js_cart_body">{% for item in car.items.all %}<tr><td>{{ item }}</td><td>{{ item.price }}</td><td>{% 包含 'cart/include/remove_cart.html'item_id=item.id %}</tr>{% 结束为 %}</tbody>
<div class="js_remove_form" style="display: none;">{% 包含 'cart/include/remove_cart.html' %}</div>

remove_cart.html:

<form class='js_cart_update_form' api="{% url 'cart:update_api' %}" action="{% url 'cart:update' %}" method='POST'>{% csrf_token %}<input class='cart_item_id' type="hidden" name="item_id" value="{{item_id }}"><input type="hidden" name="remove" value="1"><input class="btn btn-xs btn-danger js_update" type='submit' value="X"></表单>

同样是add,只是remove的隐藏值是0,输入类型submit的值是Add.

购物车中的商品正常添加,但在第一次页面重新加载和第二次 ajax 调用时删除它们时,这种情况会交替发生.

不知道为什么我会有这种奇怪的行为.

解决方案

正常,是CSRF token的原因.试试这个:

var csrftoken = $('[name="csrfmiddlewaretoken"]').val();

在你的 Ajax 请求中包含这个之后

$.ajax({...标题:{'接受': 'application/json',//如果是 json'Content-Type': 'application/json',//如果是 json"X-CSRFToken": csrftoken},凭据:'包括',....})

它对我有用

JS code for ajax request

<script type="text/javascript">
    $(document).ready(function(){
        console.log("IN")
        var cartUpdateForm = $('.js_cart_update_form')
        cartUpdateForm.submit(function(event){
            event.preventDefault()
            var thisform    = $(this);
            var method      = thisform.attr("method");
            var api         =  thisform.attr("api");
            var data_       = thisform.serialize();
            var current     = window.location.href
            console.log(method,api,current,data_)
            $.ajax({
                url:api,
                data:data_,
                type:method,
                success:function(data){
                    console.log("success")
                    console.log(data)
                    update_table(data)
                },
                error:function(data){
                    console.log('error')
                }

            });
                 function update_table(data){
                    table_ = $('.js_cart_table')
                    table_body_ = table_.find(".js_cart_body")
                    table_body_.html("")
                    remove_form = $(".js_remove_form")
                    if(data.items.length > 0){
                        $.each(data.items , function(index , val){
                            var rmf = remove_form.clone()
                            rmf.css('display','block')
                            rmf.find(".cart_item_id").val(val.id)
                            table_body_.prepend("<tr><td>"+val.name+"</td> 
<td>"+val.price+"</td><td>"+rmf.html()+"</td></tr>")
                        });
                    }
                    else
                    {
                        console.log("reloading..")
                        window.location.href = current
                    }
                }
            });
        });
    </script>

updateapi in views.py:

def update_util(request):
    pk = int(request.POST.get('item_id'))
    rest_id  = request.session['rest_id']
    restaurant = Restaurant.objects.get(pk = rest_id)
    cart_obj = Cart.objects.new_or_create(request)
    remove = request.POST.get('remove')
    item = FoodItem.objects.get(pk=pk)
    # print(pk)
    if remove == '1': 
        cart_obj.items.remove(item)
    else:
        cart_obj.items.add(item)

def update(request):
    update_util(request)
    rest_id  = request.session['rest_id']
    return redirect(reverse('restaurant:menu', kwargs={'pk':rest_id}))

def updateapi(request):
    if request.is_ajax():
        update_util(request)
        cart_obj = Cart.objects.new_or_create(request)
        print(request.POST.get('remove') ,'called')
        items = []
        data = {}
        for item in cart_obj.items.all():
            items.append({'name':item.name , 'price':item.price 
,'id':item.id})
        data_ = {'items':items , 'total':cart_obj.total , 
'subtotal':cart_obj.subtotal}
    return JsonResponse(data_)

HTML Form on which call is occuring for remove:

<table class="table js_cart_table">
<thead>
    <th>Item</th><th>Price</th><th></th>
</thead>
<tbody class="js_cart_body">
    {% for item in cart.items.all %}
            <tr><td>{{ item }}</td> <td>   {{ item.price  }}</td>
                <td>{% include 'cart/include/remove_cart.html' with 
 item_id=item.id %}</td>
            </tr>
    {% endfor %}
</tbody>

    </table>
    <div class="js_remove_form" style="display: none;">
    {% include 'cart/include/remove_cart.html' %}</div>
 </div>

remove_cart.html:

<form class='js_cart_update_form' api="{% url 'cart:update_api' %}" action=" 
{% url 'cart:update' %}"  method='POST'>
    {% csrf_token %}
    <input class='cart_item_id' type="hidden" name="item_id" value= "{{ 
item_id }}">
    <input type="hidden" name="remove" value="1">
    <input class=" btn btn-xs btn-danger js_update" type='submit' value="X">
</form>

Same is for add just hidden value of remove is 0 and value of input type submit is Add.

Items in cart are added normally but when removing them first time the page reloads and the second time the ajax call happens , this happens alternatively.

Don't know why I am having this weird behaviour.

解决方案

It is normal, it's beacause of the CSRF token. Try this:

var csrftoken = $('[name="csrfmiddlewaretoken"]').val();

And after include this in your Ajax request

$.ajax({
 ...
 headers: {
    'Accept': 'application/json', //if json
    'Content-Type': 'application/json', //if json
    "X-CSRFToken": csrftoken
    },
    credentials: 'include',
 ....
})

It worked for me

这篇关于Ajax 请求在 django 中无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆