django中template中post请求接口csrf问题

bash 复制代码
$(function () {
  $.ajaxSetup({
    headers: { "X-CSRFToken": getCookie("csrftoken") }
  });
});
 
 
// 为防止CSRF(Cross-site request forgery)跨站请求伪造,发post请求时需要在cookie中创建随机码
function getCookie(name)
{
 var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
 /*
   上面这句话相当于:
 var arr;
 var reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
  */
 if(arr=document.cookie.match(reg))
   return decodeURI(arr[2]);  //ECMAScript v3 已从标准中删除了 unescape() 函数,并反对使用它,
                 // 因此应该用 decodeURI() 和 decodeURIComponent() 取而代之。
 else
   return null;
}

参考:

https://www.jb51.net/article/182658.htm?tdsourcetag=s_pcqq_aiomsg

https://blog.csdn.net/qq_41909967/article/details/85058703

相关推荐
一瞬祈望5 小时前
PyTorch 图像分类完整项目模板实战
人工智能·pytorch·python·深度学习·分类
坐吃山猪5 小时前
BrowserUse12-源码-MCP模块
python·llm·playwright·browser-use
昔时扬尘处5 小时前
【Files Content Replace】文件夹文件内容批量替换自动化测试脚本
c语言·python·pytest·adi
咖啡の猫5 小时前
Python字典的查询操作
数据库·python·c#
smile_Iris6 小时前
Day 38 GPU训练及类的call方法
开发语言·python
嗷嗷哦润橘_6 小时前
AI Agent学习:MetaGPT项目之RAG
人工智能·python·学习·算法·deepseek
Smart-Space6 小时前
tkinter绘制组件(47)——导航边栏
python·tkinter·tinui
ULTRA??6 小时前
KD-Tree的查询原理
python·算法
电饭叔6 小时前
TypeError:unsupported operand type(s) for -: ‘method‘ and ‘int‘
开发语言·笔记·python
老歌老听老掉牙6 小时前
使用贝叶斯因子量化假设验证所需数据量
python·贝叶斯因子·假设