CSRF与Ajax轮询

时间:2013-05-12 14:21:58

标签: python ajax django

我有一些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请求。

3 个答案:

答案 0 :(得分:2)

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'));
        }
    }
});

答案 1 :(得分:0)

您需要将csrf令牌与您的帖子数据一起传递:

var date = $('article').first().find('time').text();
console.log(date);

setInterval(function() {
    $.post('pollNewEntries', {'date':date, 'csrfmiddlewaretoken': '{{csrf_token}}'}, newEntrySuccess)
}, 5000);

答案 2 :(得分:0)

只需在脚本中添加这些行即可。这是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