{{csrf_token}}给了我403紫禁城和{%csrf_token%}给了我500服务器错误
我读这两个基本相同的事情,但每一个给了我不同的错误,我不知道以后去哪个。我甚至不知道如何解决这个问题。有人可以看看我的代码,我现在挣扎了两天。{{csrf_token}}给了我403紫禁城和{%csrf_token%}给了我500服务器错误
我的HTML
<div id='notificationsLoader'>
</div>
<script>
$(document).ready(function(){
$(".notification-toggle").click(function(e){
e.preventDefault();
$.ajax({
type:"POST",
url:"{% url 'get_notifications_ajax' %}",
data: {
csrfmiddlewaretoken:"{%csrf_token%}",
},
success: function(data){
$("#notificationsLoader").html('<h3>notifications</h3>');
$(data.notifications).each(function(){
$("notificationsLoader").append(this + "<br/>")
})
console.log(data.notifications);
},
error: function(rs, e){
console.log(rs);
console.log(e);
}
})
})
})
</script>
其他HTML
<li><a class="notification-toggle" href="#">notification</a></li>
和通知是从我的Python代码
@login_required
def get_notifications_ajax(request):
notification = Notification.objects.get(id=id)
notes =[]
for note in notifications:
notes.append(str(note))
data={
"notifications":notes
}
json_data = json.dumps(data)
return HttpResponse(json_data, content_type='application/json')
有更多的这一点,但我会后刚刚这部分因为我认为错误(403和500)都说我的服务器端是错误的
While the above method can be used for AJAX POST requests, it has some inconveniences: you have to remember to pass the CSRF token in as POST data with every POST request. For this reason, there is an alternative method: on each XMLHttpRequest, set a custom X-CSRFToken header to the value of the CSRF token. This is often easier, because many javascript frameworks provide hooks that allow headers to be set on every request.
所以,你可以通过csrftoken值作为X-CSRFToken
头,它可以从饼干(我加getCookie
功能需要)获取。您可以轻松地发送之前setuping你与ajaxSetup Ajax请求做到这一点,请参见下面的代码:
// Source https://docs.djangoproject.com/en/1.7/ref/contrib/csrf/#ajax
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;
}
$(".notification-toggle").click(function(e){
e.preventDefault();
var token = getCookie('csrftoken');
$.ajaxSetup({'headers': {'X-CSRFToken': token}});
// $.ajax...
Altrnatively你可以尝试从更换您的数据:
data: {
csrfmiddlewaretoken:"{%csrf_token%}",
},
到
data: {
csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
},
哦,好吧,这是我第一次听说这个我肯定会试试这个谢谢 – winixxee
我得到Uncaught ReferenceError:饼干没有定义 – winixxee
哦,是的,一秒 –