我有一些AJAX,它每5秒轮询一次服务器:
var date = $('article').first().find('time').text();
console.log(date);
setInterval(function() {
$.post('pollNewEntries', {'date':date}, newEntrySuccess)
}, 5000);不幸的是,每次AJAX尝试轮询服务器时,我都会收到一个403错误,说明我发出了一个无效的CSRF请求。我以前在表单中使用过AJAX,并在表单中包含了CSRF令牌,但我不确定如何使用像上面这样的无表单AJAX请求。
发布于 2013-05-13 17:40:56
这个问题的解决方案在Django文档中描述:https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
将此代码添加到js的顶部:
$.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'));
}
}
});发布于 2013-05-12 23:53:41
您需要将csrf令牌与您的帖子数据一起传递:
var date = $('article').first().find('time').text();
console.log(date);
setInterval(function() {
$.post('pollNewEntries', {'date':date, 'csrfmiddlewaretoken': '{{csrf_token}}'}, newEntrySuccess)
}, 5000);发布于 2013-05-13 00:30:30
只需在脚本中添加这些行即可。下面是一个使用coffeescript编写的示例:
### CSRF methods ###
csrfSafeMethod = (method) ->
# these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method))
$.ajaxSetup(
crossDomain: false
beforeSend: (xhr, settings) ->
if !csrfSafeMethod(settings.type)
xhr.setRequestHeader("X-CSRFToken", $.cookie('csrftoken'))
)阅读文档:CSRF
另一方面,正如user1427661向您建议的那样,使用HTTP GET方法将比使用POST更好,因为您只需要读取数据,而不需要写入任何内容。请参阅W3 docs。
https://stackoverflow.com/questions/16508332
复制相似问题