解决Django中在.js文件中用ajax请求后端,找不到CSRF问题
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 USERNAME = ''; $('document').ready(function(){ $('#login_submit').click(function(){ var csrftoken = getCookie('csrftoken'); var username = $('#username').val(); var password = $('#password').val(); $.ajax({ cache: false, type: "POST", url: "/signin/", dataType:'json', async: true, data:{ username: username, //用户名 password: password //密码 }, success: function(data) { if (data.status == 'fail') { alert('用户名或密码错误') } if (data.status == 'fail1') { alert('用户名必填并且密码必须要五位以上') } if(data.status == 'success') { window.location.href = "/index"; } }, beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } }); });