我正在尝试将一些数据发布到API(Django REST Framework) 我读过: "how to include CSRF tokens in AJAX requests."
但是上面的代码仍无效......它在控制台上发出了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);
}
});
});