經過獲取隱藏的input標籤中的csrfmiddlewaretoken值,放置在data中發送。python
$.ajax({ url: "/cookie_ajax/", type: "POST", data: { "username": "yang", "password": 123, // 使用jQuery取出csrfmiddlewaretoken的值,拼接到data總 "csrfmiddlewaretoken": $("[name="csrfmiddlewaretoken"]").val() }, success: function(data){ console.log(data); } })
經過獲取返回的cookie中的字符串,放置在請求頭中發送。jquery
注意: 須要引入一個jquery.cookie.js插件。ajax
$.ajax({ url: "/cookie_ajax/", type: "POST", // 從Cookie取csrftoken, 並設置到請求頭中 headers: {"X-CSRFToken": $.cookie("csrftoken")}, data: { "username": "yang", "password": 123 }, success: function(data){ console.log(data) } })
或者用本身寫一個getCookie方法:django
function getCookie(name){ var cookieValue = null; if (document.cookie && document.cookie !== ""){ var cookies = document.cookie.split(";"); for (var i = 0; i < cookies.length; i++){ var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + "=")){ cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } var csrftoken = getCookie("csrftoken");
每一次都這麼寫太麻煩了,可使用$.ajaxSetup()方法爲ajax請求統一設置。cookie
function csrfSafeMethod(method){ // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method); } $.ajaxSetup({ beforeSend: function(xhr, settings){ if (!csrfSafeMethod(settings.type) && !this.crossDomain){ xhr.setRequestHeader("X-CSRFToken", csrftoken); } } })
注意:
若是使用從cookie中取csrftoken的方式,須要確保cookie存在csrftoken值。
ui
若是你的視圖渲染的HTML文件中沒有包含{% csrf_token %}, Django可能不會設置CSRFtoken的cookie。this
這個時候須要使用ensure_csrf_cookie()裝飾器強制設置Cookie。url
django.views.decorators.csrf import ensure_csrf_cookie @ensure_csrf_cookie def login(request): pass