我的 jQuery
函数看起来像
$(function() {
// activate "New" buttons if input is not empty
$('form input[type="text"]').live('keyup', function() {
var val = $.trim(this.value);
$(this).next("button").prop('disabled', val.length === 0);
});
$("body").on("submit","form",function(e){
// do not submit the form
e.preventDefault();
// handle everything yourself
var $form = $(this);
var title = $form.closest('.video-detail').find('.title').text();
var entryTitle = $form.find('.input-small').val();
console.debug(title);
console.debug(entryTitle);
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});
// send the data to the server using .ajax() or .post()
$.ajax({
type: 'POST',
url: 'addVideo',
data: {
video_title: title,
csrfmiddlewaretoken: '{{ csrf_token }}'
},
}).done(function(){
alert('done');
});
});
});
这是基于答案 Django CSRF check failing with an Ajax POST request
我的 html
看起来像
<form class="new-playlist form-inline" onclick="event.stopPropagation()">{% csrf_token %}
<input type="text" class="input-small">
<button class="btn btn-danger create-playlist-button" type="submit" disabled="disabled">New</button>
</form>
当我在 Firefox 中调试代码时,我看到帖子值为
csrfmiddlewaretoken {{ csrf_token }}
video_title The Who - Who Are You?
如何填充 {{ csrf_token }}
值?
谢谢
最佳答案
就我而言,我有一个模板,我不想在其中包含 <form></form>
元素。但我仍然想使用 jQuery 发出 AJAX POST 请求。
即使我遵循了 django 文档 ( https://docs.djangoproject.com/en/1.5/ref/contrib/csrf/ ),由于 CSRF cookie 为空,我也收到 403 错误。解决方案在同一页面中,提到 ensure_csrf_cookie
装饰器。
当我将其添加到我的 views.py
顶部时,我的 CSRF cookie 确实被设置了:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
另外,请注意,在这种情况下,您不需要标记/模板中的 DOM 元素:{% csrf_token %}
关于jQuery:为 Django 设置 CSRF token 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11812694/