2013-05-12 104 views
1

我有一些AJAX来轮询每5秒服务器:CSRF使用Ajax轮询

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

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

不幸的是,我每次AJAX尝试轮询服务器时得到一个403错误,说明我已经无效的CSRF请求。我之前使用过AJAX,并且在表单中包含了CSRF标记,但是我不确定我会如何处理上述的无格式AJAX请求。

+1

https://docs.djangoproject.com/en/dev/ref/contrib/csrf /#ajax – dm03514 2013-05-12 14:30:58

+1

你为什么使用POST? GET更适合于只从数据库中取出的动作,而不需要CSRF。 – 2013-05-12 14:40:53

+0

因为我需要传递页面上最新文章的日期。可以GET做到这一点? – user1427661 2013-05-12 15:39:09

回答

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

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

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

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

即使它不在HTML模板(这是一个js文件),它会工作吗? – user1427661 2013-05-12 16:02:22

+0

哦,我以为它的模板。但你可以做的一件事就是将'