解决 Ajax 发送 post 请求出现 403 Forbidden 的三种方式

众所周知前端向后台发送 post 请求时,必须验证 csrf,否则会报错 403 Forbidden。使用 Django Form 表单可以直接在表单里面添加 {% csrf_token %} 即可,要是通过 Ajax 发送请求又该怎么办?下面提供三种解决办法:

<ul id="ddd">
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<button id="btn" type="button">Ajax 发送</button>

1. 方式一

<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script>
    $('#btn').click(function () {
        var li_content = [];
        $('#ddd').children('li').each(function () {
           li_content.push($(this).html());
        });
        console.log(li_content);

        $.ajax({
            url: '/webs/test_json/',
            type: 'post',
            data: {
                'li_list': JSON.stringify(li_content),
                 csrfmiddlewaretoken: '{{ csrf_token }}'		// 添加这句
            },
            success: function (arg) {
                console.log(arg);
            }
        })
    })

</script>

2. 方式二

方式二仅在 Django 中适用,因为 {% csrf_token %} 是 Django 的模板语言,它会生成一个隐藏的 input 标签

<ul id="ddd">
    {% csrf_token %}		<!--添加这句会生成一个隐藏的 input 标签,name='csrfmiddlewaretoken'-->
    <li>1</li>
    <li>2</li>
    <li>3</li>
</ul>
<button id="btn" type="button">Ajax 发送</button>
<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script>
    $('#btn').click(function () {
        var li_content = [];
        $('#ddd').children('li').each(function () {
           li_content.push($(this).html());
        });
        console.log(li_content);

        $.ajax({
            url: '/webs/test_json/',
            type: 'post',
            data: {
                'li_list': JSON.stringify(li_content),
                 csrfmiddlewaretoken:$('[name="csrfmiddlewaretoken"]').val()	// 添加这句,去获取 input 的值
            },
            success: function (arg) {
                console.log(arg);
            }
        })
    })

</script>

3. 方式三

因为 cookie 中同样存在 csrftoken ,所以可以在 js 中获取:$.cooke("cstftoken"),并将其添加到请求头中发送。

1、直接添加请求头:

 $.ajax({
            url: '/webs/test_json/',
		   headers: { "X-CSRFtoken":$.cookie("csrftoken")},
            type: 'post',
            data: {
                'li_list': JSON.stringify(li_content)
            },
            success: function (arg) {
                console.log(arg);
            }
        })
    })

2、如果页面有多个 Ajax,那么可以设置全局的:

发送请求前会事先执行 $.ajaxSetup() 方法,它会从 cookie 中获取 csrftoken

$.ajaxSetup({
    beforeSend: function (xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
        }
    }
});


$.ajax({
    url: '/webs/test_json/',
    type: 'post',
    data: {
        'li_list': JSON.stringify(li_content)
    },
    success: function (arg) {
        console.log(arg);
    }
})

3、如果想要实现在当 get 方式的时候不需要提交 csrftoken,当 post 的时候需要,实现这种效果的代码如下:

<script src="{% static 'js/jquery-3.1.1.js' %}"></script>
<script type="text/javascript" src="/static/js/jquery.cookie.js"></script>
<script>
    $('#btn').click(function () {
        var li_content = [];
        $('#ddd').children('li').each(function () {
            li_content.push($(this).html());
        });
        console.log(li_content);

        function csrfSafeMethod(method) {
            // these HTTP methods do not require CSRF protection
            return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
        }

        /*
         全局Ajax中添加请求头X-CSRFToken,用于跨过CSRF验证
         */
        $.ajaxSetup({
            beforeSend: function (xhr, settings) {
                if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
                    xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'));
                }
            }
        });


        $.ajax({
            url: '/webs/test_json/',

            type: 'post',
            data: {
                'li_list': JSON.stringify(li_content)
            },
            success: function (arg) {
                console.log(arg);
            }
        })
    })

</script>

Tips:一定要导入 jquery.cookie.jsjquery-3.3.1.js 文件 !!!

posted @ 2019-06-10 11:43  Hubery_Jun  阅读(37114)  评论(0编辑  收藏  举报