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

相关推荐
ZhengEnCi4 小时前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风9 小时前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python
明月_清风10 小时前
Python 消失的内存:为什么 list=[] 是新手最容易踩的“毒苹果”?
后端·python
Flittly1 天前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(3)TodoWrite (待办写入)
python·agent
千寻girling1 天前
一份不可多得的 《 Django 》 零基础入门教程
后端·python·面试
databook1 天前
探索视觉的边界:用 Manim 重现有趣的知觉错觉
python·动效
明月_清风1 天前
Python 性能微观世界:列表推导式 vs for 循环
后端·python
明月_清风1 天前
Python 性能翻身仗:从 O(n) 到 O(1) 的工程实践
后端·python
helloweilei2 天前
python 抽象基类
python
用户8356290780512 天前
Python 实现 PPT 转 HTML
后端·python