CSRF之Ajax请求
CSRF之Ajax请求
A:Ajax提交数据是,携带的CSRF在data中:
csrf.html
<form method="POST" action="/csrf.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form> <script src="/static/jquery-1.12.4.js"></script> <script> function submitForm(){ var csrf = $('input[name="csrfmiddlewaretoken"]').val(); var user = $('#user').val(); $.ajax({ url: '/csrf.html', type: 'POST', data: {"user":user, 'csrfmiddlewaretoken':csrf}, success:function(arg){ console.log(arg); } }) } </script>
B:Ajax提交数据是,携带的CSRF在请求头中:
用jQuery.cookie 对cookie进行操作。
<form method="POST" action="/csrf.html"> {% csrf_token %} <input id="user" type="text" name="user" /> <input type="submit" value="提交"/> <a onclick="submitForm();">Ajax提交</a> </form> <script src="/static/jquery-1.12.4.js"></script> <script src="/static/jquery.cookie.js"></script> <script> function submitForm(){ var token = $.cookie('csrftoken'); var user = $('#user').val() $.ajax({ url: '/csrf.html', type: 'POST', headers:{'X-CSRFToken': token}, data: { "user":user}, success:function(arg){ console.log(arg); } }) } </script>
-------- END --------