我正在尝试将一些数据发布到 API(Django REST 框架)我读到: “如何在 AJAX 请求中包含 CSRF 令牌。”
但上面的代码仍然无法正常工作......它在控制台上给出了 FORBIDDEN 403 消息(提前致谢):
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script src="jquery.cookie.js"></script>
$( document ).ready(function() {
$.cookie('csrftoken', 'valueoftoken');
var csrftoken = $.cookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
var filme={"name": "PROVAJSON", "categorie": "all_ages", "is_available": true};
$.ajax({
type: "POST",
url: myurltopost,
contentType: "application/json; charset=utf-8",
data: filme,
dataType:"json",
success: function(result){
alert("done);
}
});
});