网站使用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')
#...