我有这个jquery代码片段,应该可以获取csrf令牌,因此ajax请求可与Django一起使用。
/*CSRF Code */
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
/* End CSRF Code */
$(document).ready(function() {
var username_ok = false;
var email_ok = false;
var csrftoken = $.cookie('csrftoken');
$('.signin-btn').click(function(event) {
var username = $('#username-2').val();
var password = $('#password').val();
if (username && password) {
event.preventDefault();
var data = {username, password};
$.ajax({
url: "/signin-ajax",
type: "POST",
dataType: 'json',
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && sameOrigin(settings.url)) {
// Send the token to same-origin, relative URLs only.
// Send the token only if the method warrants CSRF protection
// Using the CSRFToken value acquired earlier
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
data: JSON.stringify(data),
success: function(response){
var status = response['status'];
if (status == 'ok') {
document.location.href = '/';
} else {
var error = response['error'];
$('.signin-error-msg').removeClass('hidden').text(error);
$('.activate-account').removeClass('hidden');
}
}
});
/* End Ajax Call */
}
});
});
这在我进行了大多数测试的ubuntu上有效,现在我切换到Windows,它给了我403错误,但未找到csrf令牌。
禁止(403) CSRF验证失败。请求中止。
You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties.
If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests.
Help
Reason given for failure:
CSRF cookie not set.