Javascript Django项目中基于AJAX的CSRF令牌post
所以我发现了错误,它出现在我的HTML中。我刚刚添加了Javascript Django项目中基于AJAX的CSRF令牌post,javascript,jquery,ajax,django,csrf,Javascript,Jquery,Ajax,Django,Csrf,所以我发现了错误,它出现在我的HTML中。我刚刚添加了{%csrf\u token%},效果很好:)谢谢大家的帮助 (我使用了第一个答案中提供给我的JS代码片段,但我仍然 得到403禁止错误!)我会做错什么 我最近学习了JS,并尝试了以下用于AJAX POST的JS代码,但我遇到了403错误。做了一些进一步的研究,发现我需要传递一个CSRF令牌。我在网上浏览了很多教程,但我能找到的唯一解决方案是JQuery,我不知道这种语法是如何工作的。我需要知道如何为django项目通过基于Javascrip
{%csrf\u token%}
,效果很好:)谢谢大家的帮助
(我使用了第一个答案中提供给我的JS代码片段,但我仍然
得到403禁止错误!)我会做错什么
我最近学习了JS,并尝试了以下用于AJAX POST的JS代码,但我遇到了403错误。做了一些进一步的研究,发现我需要传递一个CSRF令牌。我在网上浏览了很多教程,但我能找到的唯一解决方案是JQuery,我不知道这种语法是如何工作的。我需要知道如何为django项目通过基于Javascript AJAX的post传递CSRF令牌。我的代码是
var upvoteBtn = document.querySelector('#upvote');
var downvoteBtn = document.querySelector('#downvote');
upvoteBtn.addEventListener('click', jL);
downvoteBtn.addEventListener('click', cL);
function jL(event) {
document.getElementById("upvote").style.display='none';
document.getElementById("downvote").style.display='none';
var http = new XMLHttpRequest ();
var url = 'entered my url here';
var data = 'title=Post%20Title&body=Body';
var method = 'POST';
http.open(method, url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
http.setRequestHeader("X-CSRFToken", csrftoken);
http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE && http.status === 200){
document.getElementById("first").innerHTML = "this post has been voted";
console.log("upvote given");
}
else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200){
console.log("error!", http.responseText);
}
};
http.send(data);
}
function cL(event){
document.getElementById("upvote").style.display='none';
document.getElementById("downvote").style.display='none';
var http = new XMLHttpRequest ();
var url = 'entered my url here';
var data = 'title=Post%20Title&body=Body';
var method = 'POST';
http.open(method, url, true);
http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
http.setRequestHeader("X-CSRFToken", csrftoken);
http.onreadystatechange = function() {
if (http.readyState === XMLHttpRequest.DONE && http.status === 200){
document.getElementById("first").innerHTML = "got downvoted";
console.log("downvoted!");
}
else if (http.readyState === XMLHttpRequest.DONE && http.status !== 200){
console.log("error!", http.responseText);
}
};
http.send(data);
}
//function for CSRF token
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var csrftoken = getCookie('csrftoken');
var-upvoteBtn=document.querySelector(“#upvote”);
var downvoteBtn=document.querySelector(“#downvote”);
upvoteBtn.addEventListener('click',jL);
downvoteBtn.addEventListener('click',cL');
职能jL(事件){
document.getElementById(“upvote”).style.display='none';
document.getElementById(“downvote”).style.display='none';
var http=newxmlhttprequest();
var url='在此处输入我的url';
变量数据='title=Post%20Title&body=body';
var方法='POST';
open(方法、url、true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
setRequestHeader(“X-CSRFToken”,CSRFToken);
http.onreadystatechange=函数(){
if(http.readyState==XMLHttpRequest.DONE&&http.status==200){
document.getElementById(“first”).innerHTML=“此帖子已被投票”;
控制台日志(“向上投票”);
}
else if(http.readyState==XMLHttpRequest.DONE&&http.status!==200){
log(“错误!”,http.responseText);
}
};
http.send(数据);
}
职能cL(活动){
document.getElementById(“upvote”).style.display='none';
document.getElementById(“downvote”).style.display='none';
var http=newxmlhttprequest();
var url='在此处输入我的url';
变量数据='title=Post%20Title&body=body';
var方法='POST';
open(方法、url、true);
http.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
setRequestHeader(“X-CSRFToken”,CSRFToken);
http.onreadystatechange=函数(){
if(http.readyState==XMLHttpRequest.DONE&&http.status==200){
document.getElementById(“first”).innerHTML=“被否决”;
log(“被否决的!”);
}
else if(http.readyState==XMLHttpRequest.DONE&&http.status!==200){
log(“错误!”,http.responseText);
}
};
http.send(数据);
}
//CSRF令牌的功能
函数getCookie(cname){
变量名称=cname+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);
对于(var i=0;i您需要调用:
xhr.setRequestHeader("X-CSRFToken", csrftoken);
当您准备xhr
请求时。(在您的示例中,xhr
被命名为http
)
您可以从cookie中获取csrftoken
,但是为了实现这一点,您需要实现getCookie
函数
像这样的事情应该可以做到:
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
var csrftoken = getCookie('csrftoken');
函数getCookie(cname){
变量名称=cname+“=”;
var decodedCookie=decodeURIComponent(document.cookie);
var ca=decodedCookie.split(“;”);
对于(var i=0;i将这段代码添加到JS中:
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 = $.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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
if (!csrfSafeMethod(http.responseType) && sameOrigin(http.responseUrl)) {
http.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
函数getCookie(名称){
var-cookieValue=null;
if(document.cookie&&document.cookie!=''){
var cookies=document.cookie.split(“;”);
对于(变量i=0;i
基本上,您需要将CSRF令牌添加到标题中。如果有人知道这段代码会很好的话,我找不到找到这段代码的链接。嘿,我尝试使用您的注释,但一开始我遇到了一个错误,http没有定义,后来我得到了未捕获的引用错误:在HTMLButtonElement.jL(button.js:49)中没有定义csrftoken当我将http定义为一个变量时,正如上面提到的,我已经在我的代码中做了。我只是在我为这个问题粘贴的代码末尾添加了你给我的代码。我无法复制你的代码,所以你必须给出详细的错误。给出错误发生的行是没有帮助的。无论如何,你必须添加我的代码ter您的内容类型
标题。好吧,函数可以退出,但是if
必须退出。我已经更新了原始问题中的代码,并添加了错误消息的屏幕截图。虽然新更新的代码没有您给我的代码,但我也尝试了您的方法,保留了3个函数,但没有if stat右翼联合国
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 = $.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;
}
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
function sameOrigin(url) {
// test that a given url is a same-origin URL
// url could be relative or scheme relative or absolute
var host = document.location.host; // host + port
var protocol = document.location.protocol;
var sr_origin = '//' + host;
var origin = protocol + sr_origin;
// Allow absolute or scheme relative URLs to same origin
return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
(url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
// or any other URL that isn't scheme relative or absolute i.e relative.
!(/^(\/\/|http:|https:).*/.test(url));
}
if (!csrfSafeMethod(http.responseType) && sameOrigin(http.responseUrl)) {
http.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}