ajax调用csfr令牌的问题 [英] Issue with ajax call csfr token

查看:69
本文介绍了ajax调用csfr令牌的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加一个ajax调用,以更改列表状态(在已列出和未列出之间),在提交表单时我在浏览器的控制台中出现403禁止错误,我进行了一些检查,结果发现Django由于缺少csrf令牌而禁止使用该表格,但是我的JavaScript不好,因此不胜感激。

I am trying to add an ajax call that changes the status of a listing, between listed and unlisted, when submitting the form I am having a 403 forbidden error in the console of the browser, I made some checking and it appears that Django is forbidding the form because of a lack of csrf token, however I am not good in javascript, so any help would be appreciated.

这是我认为的代码:

@require_POST
@ajax_required
@login_required

def unlist_ajax(request):
    pk = request.POST.get('pk', None)
    is_visible = request.POST.get('is_visible', None)
    if pk and is_visible:
        listing = get_object_or_404(Listing, pk=pk)
        if is_visible == 'true':
                listing.is_visible = False
                listing.save()
                messages.success(request, _("Listing unlisted"))
                return JsonResponse({'status': 'ok'})

         else:
                listing.is_visible = True
                listing.save()
                messages.success(request, _("Listing re-listed"))
                return JsonResponse({'status':'ok'})

这是模板脚本:

在模板顶部的标题中:

  <script>
 function unlistPostAjax(listing_id, is_visible) {
var confirmation = confirm("{% trans 'are you sure you want to change the status of your listing?' %}");
if (confirmation) {
$.post("{% url 'dashboard:unlist_ajax' %}", {pk: listing_id, is_visible: is_visible}, function (response) {
console.log('sending delete query'); location.reload();
})
}
}


    </script>

在身体底部:

 <script src="{% static 'js/jquery.cookie.js' %}"> </script>
<script>
        $(document).ready(function () {
            var csrftoken = $.cookie('csrftoken');
            function csrfSafeMethod (method) {
                // These HTTP methods do not require CSRF protection
                return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
            }
            $.ajaxSetup({
                beforeSend: function (xhr, settings) {
                    if(!csrfSafeMethod(settings.type) && !this.crossDomain) {
                        // Set X-CSRFToken HTTP Header
                        xhr.setRequestHeader("X-CSRFToken", csrftoken);
                    }
                }
            });
        });
    </script>


推荐答案

您可以将其添加到<$的顶部c $ c>< script> ,或者如果您有基本的html模板,也可以将其放在其中。

You can add this to the top of your <script> or if you have a base html template you can put this in there too.

{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
</script>

相信您只需要在定义的脚本上方添加csrf,但这就是整个实现当前使用。我没有问题。

Believe you just need to add the csrf above the script you defined, but this is the whole implementation I currently use. I have no issues.

这篇关于ajax调用csfr令牌的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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