gpt4 book ai didi

javascript - {{csrf_token}} 给我 403 Forbidden 和 {%csrf_token%} 给我 500 服务器错误

转载 作者:行者123 更新时间:2023-11-28 18:32:27 24 4
gpt4 key购买 nike

我读到这两个基本上是同一回事,但每个都给我不同的错误,我不确定该去哪一个。我什至不知道如何解决这个问题。有人可以看看我的代码吗,我已经为此苦苦挣扎了两天。

我的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>

通知来 self 的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)是说我的服务器端错误

最佳答案

来自 Django Project Documenation :

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 header 传递,它可以从 cookie 中获取(我已经为该需求添加了 getCookie 函数)。您可以通过使用 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...

或者,您可以尝试从以下位置替换您的数据:

data: {
csrfmiddlewaretoken:"{%csrf_token%}",
},

data: {
csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val()
},

关于javascript - {{csrf_token}} 给我 403 Forbidden 和 {%csrf_token%} 给我 500 服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35642076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com