我正在尝试使用ajax发出发布请求
<div>
<h4>Comments</h4>
<form action="#" method="post">
<textarea class="form-control" rows="5" name='comment' id="commentContent"></textarea>
<br>
<button class="btn btn-primary" id="commentBtn">Post Your Comment</button>
</form>
</div>
</div><!--/class="col-xs-8 col-md-8">-->
</div><!-- row -->
<script src="/static/js/jquery-3.3.1.js"></script>
<script src="/static/js/jquery-csrf.js"></script>
<script>
$(document).ready(function () {
var article_id = {{ article.id }};
var num_pages = {{ page.num_pages }};
$('#commentBtn').on('click', function (e) {
e.preventDefault();
alert('clicked');
var comment = $('#commentContent').val();
var param = {
"article_id": article.id,
"content": comment,
};
$.post('/article/comment/create/', param, function (data) {
var ret = JSON.parse(data);
if ((ret['status'] = 'ok')) {
$('#commentConent').val('');
window.location.href =
'/article/detail/{{ article.id }}?page_number=' + num_pages;
} else {
alert(ret['msg']);
}
});
});
});
</script>
提交表单后,它抛出“禁止”错误
Forbidden (403) CSRF verification failed. Request aborted.
我尝试了不同版本的jQuery,问题仍然没有解决。
jquery-csrf.js
已根据官方文档正确放置,并已由服务器成功加载。”
[24/Jun/2018 21:58:55] "GET /static/js/jquery-3.3.1.js HTTP/1.1" 304 0
[24/Jun/2018 21:58:55] "GET /static/js/jquery-csrf.js HTTP/1.1" 304 0
jquery-csrf.js
// using jQuery
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
可能是什么问题?