1. 程式人生 > >Django,Ajax提交csrf_token處理

Django,Ajax提交csrf_token處理

$.ajax url log pos ati code csr post user

Ajax提交數據時候,攜帶CSRF:
a. 放置在data中攜帶

<form method="POST" action="/csrf1.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: ‘/csrf1.html‘, type: ‘POST‘, data: { "user":user,‘csrfmiddlewaretoken‘: csrf}, success:function(arg){ console.log(arg); } }) }
</script> b. 放在請求頭中 <form method="POST" action="/csrf1.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: ‘/csrf1.html‘, type: ‘POST‘, headers:{‘X-CSRFToken‘: token}, data: { "user":user}, success:function(arg){ console.log(arg); } }) } </script>

Django,Ajax提交csrf_token處理