Django ajax请求 403错误

本文介绍如何在Django+layui框架中通过ajax解决数组传递问题,并绕过csrf验证,实现前后端数据交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网站使用Django+layui,在向后台发送数据请求需要传递一个数组,使用layui.table的动态渲染,貌似不能实现。无法传递数组信息到views后台的接口。然后根据网络搜索得知可以使用ajax进行post传递数组,但又因为csrf_protected,接口总是返回403错误,尝试了几个方案都无法搞定,最后根据Django csrf文档说明在ajax post请求里添加头部信息,最后实现。

//获取csrftoken
	function getCookie(name) {
    	let cookieValue = null;
    	if (document.cookie && document.cookie !== '') {
        	const cookies = document.cookie.split(';');
        	for (let i = 0; i < cookies.length; i++) {
            	const cookie = cookies[i].trim();
            	// 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;
	}
	const csrftoken = getCookie('csrftoken');
	
//ajax请求
$.ajax({
                url : "/make_match_result",
                type : "post",
                headers: {"X-CSRFToken": csrftoken},
                traditional : true,// 这里设置为true,不然后台接收到的参数会带上[],导致数据无法正常接收
                data : {
                    "scl_nms" : snms,
                    "maj_nms" : mnms
                },
                success : function(resp) {
                	if(resp.code == 0) {
                		console.log('sucess')

                		var tdata = resp.data;
                		console.log(tdata)
                		table.render({
    						elem: '#res_tbl'
    						,data:tdata
    						,cols: [[
      							{field:'name',  title: '名称', width:180}
      							,{field:'mscore', title: '分数', width:110}
    							]]
    						,height: 800
  							});
                	}else {
                		layer.msg('请求错误');
                	}
                }
            });
#views.py 接口
def make_match_result(request):
    snms = request.POST.getlist('scl_nms')
    mnms = request.POST.getlist('maj_nms')
    #...
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值