django的csrf

如果是ajax提交,可以按照下面的方式处理

  <script src="/static/jq/jquery-3.3.1.js"></script>
    <script src="/static/jq/jquery.cookie.js"></script>
    <script>
        $(function () {
            ajax_buttion()
        })

        function ajax_buttion() {
            $("#btn").bind("click",function () {
                $.ajax(
                    {
                        url:"/test/app1/",
                        type:"post",
                        data:{
                            username:"root",
                            pwd:"admin"
                        },
                        headers:{
                            "X-CSRFToken":$.cookie("csrftoken")
                        },
                        sucess:function (data) {
                            console.log(data)

                        }
                    }


                )

            })
        }
    </script>

  

 可以设置一个全局的设置,然后在$(function){

}中执行函数

        $(function () {
            ajax_buttion()
            $.ajaxSetup()
        })

  

如果是form表单提交,则可以按照下面的方式处理

    <form action="/test/app1/" method="post">
        {% csrf_token %}
        <input type="text" name="uname">
        <input type="submit" value="submit">
        <input type="button" value="ajax" id="btn">
    </form>

  

然后返回使用render的方式返回

def test(request):
    # int("hahah")
    # print(settings.C)
    print("test------->views",time.time())

    print(request.method)
    print("_".center(100,"-"))
    print(request)
    # return HttpResponse("last_app1")
    return render(request,"test.html")

  

猜你喜欢

转载自www.cnblogs.com/bainianminguo/p/9452495.html