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

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

问题描述

用于ajax请求的JS代码

 < script type = text / javascript> 
$(document).ready(function(){
console.log( IN)
var cartUpdateForm = $('。js_cart_update_form')
cartUpdateForm.submit(function (事件){
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( 成功)
console.log(data)
update_table(data)
},
error:function(data){
console.log('error' )
}

});
函数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_前缀( html()+< / td>< / tr>)
});
}
其他
{
console.log( reloading ..)
window.location.href =当前
}
}
});
});
< / 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)
如果删除=='1':
cart_obj.items.remove(item)
else:
cart_obj.items.add(item)

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

def updateapi(request):
如果request.is_ajax():
update_util(request)
cart_obj = Cart.objects.new_or_create(request)
print(request.POST.get('remove'),'call')
items = []
数据= {} 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表单:

 < table class = table js_cart_table> 
< thead>
thth项/ thth价格/ ththth / thth。
< / thead>
< tbody class = js_cart_body>
{cart.items.all%中商品的%}
< tr>< td> {{item}}< / td> < td> {{item.price}}< / td>
< td> {%包括‘cart / include / remove_cart.html’和
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: p>

 < form class ='js_cart_update_form'api = {%url'cart:update_api'%} action = 
{%url'cart:update'%} method ='POST'>
{%csrf_token%}
<输入类别= 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>

相同是用于添加,而remove的隐藏值是0,输入类型Submit的值是Add。 / p>

购物车中的项目通常会添加,但是在第一次重新加载页面时以及第二次进行ajax调用时将其删除时,就会交替发生。



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

解决方案

这很正常,因为CSRF令牌。
尝试以下操作:

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

然后将其包含在您的Ajax请求中

  $。ajax({
...
标头:{
'Accept':'application / json',//如果json
'Content-Type':'application / json',//如果json
X-CSRFToken:csrftoken
},
凭据:'include',
。 ...
})

对我有用


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天全站免登陆