微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

解决 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 文件 !!!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐