码迷,mamicode.com
首页 > Web开发 > 详细

django下ajax请求403(FORBIDDEN)的解决办法

时间:2015-08-08 18:24:17      阅读:250      评论:0      收藏:0      [点我收藏+]

标签:django   ajax   post   403   forbidden   

环境

django 1.8.3

错误描述

POST http://localhost:8000/ajax_query_data/ 403 (FORBIDDEN)

解决办法

django官方文档上如下内容:

https://docs.djangoproject.com/en/dev/ref/csrf/#ajax

AJAX
While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many JavaScript frameworks provide hooks that allow headers to be set on every request.
As a first step, you must get the CSRF token itself. The recommended source for the token is the csrftoken cookie, which will be set if you’ve enabled CSRF protection for your views as outlined above.
官方文档里面有范例,基本原理就是在post数据里面添加csrf信息

总结并试了下,将下面代码加到js文件里面问题可解决:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

var csrftoken = getCookie('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) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

版权声明:本文为博主原创文章,欢迎转载,转载请注明出处。

django下ajax请求403(FORBIDDEN)的解决办法

标签:django   ajax   post   403   forbidden   

原文地址:http://blog.csdn.net/xxm524/article/details/47359485

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!