今天接触这个框架发现的问题,某些情况下,json传过来了,对应表格报错或提示无数据,情况截图如下:
LayUi 对传过来的 Json 有严格的要求,一般情况下,要求要有4个参数,分别为:
code:0 //数据状态
msg:"" //状态信息
count:1000 //数据总数
data:[] //数据列表
若传过来的 Json 包含这四个参数,且参数名一样,则表格读数据不会出问题。若参数名和上述的不一样,则需要转换下,具体方法如下:
response:{
statusName: '自定义的参数名称' ,// 对应 code
msgName: '自定义的参数名称' , // 对应 msg
countName: '自定义的参数名称' , // 对应 count
dataName: '自定义的参数名称' // 对应 data
}
上述代码 写在 table.render({}) 内。
经过测试,发现有两个字段不是必要的,分别是,msg 和 count 。若不传或参数名对不上时不转换,前台表格页面依旧会显示出数据,必要的参数只有 code 和 data 。
官方文档地址:传送门
文档中,statusCode 不需要写,写的话 数据会显示不成功。
下面用例子再说明下:
表格页代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="https://res.layui.com/layui/rc/css/layui.css?t=20181101-1" media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<table class="layui-hide" id="test"></table>
<script src="https://res.layui.com/layui/rc/layui.js?t=20181101-1"></script>
<!-- 注意:如果你直接复制所有代码到本地,上述js路径需要改成你本地的 -->
<script>
layui.config({
base: './dist/' //指定 layuiAdmin 项目路径
,version: '1.2.1'
}).use('table', function() {
var table = layui.table;
table.render({
elem: '#test'
,url: 'json/default.json'
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,cols: [
[{
field: 'id',width: 80,title: 'ID',sort: true
}, {
field: 'username',width: 80,title: '用户名'
}, {
field: 'sex',width: 80,title: '性别'
}]
]
});
});
</script>
</body>
</html>
对应的default.json如下:
{
"code": "0",
"msg": "",
"data": [{
"id": "1",
"username": "hello",
"sex": "boy"
}, {
"id": "2",
"username": "world",
"sex": "boy"
}, {
"id": "3",
"username": "too",
"sex": "boy"
}]
}
显示的结果如下图:
这种是传参默认符合Layui中Table配置的结果,若仅更改参数名称,即将JSON中的code改为status,得到的结果如下图:
若仅将JSON参数列表中的参数名data更改为rows,得到的结果如下图:
实际上,接口对应的请求都是成功的,只是Layui显示不出来,碰到上述问题,有两个解决办法:
第一,后端改,使传过来的参数名符合Layui所需要;
第二,前端改,需要加代码,Layui有示例,下面也简单说下:
传的JSON,更改code为status,data为rows:
{
"status": "0",
"msg": "",
"rows": [{
"id": "1",
"username": "hello",
"sex": "boy"
}, {
"id": "2",
"username": "world",
"sex": "boy"
}, {
"id": "3",
"username": "too",
"sex": "boy"
}]
}
现在页面上表格显示不出来数据,还报错,和上面报的的截图一样,更改html上的代码,如下所示(只显示主要的):
<!-- 省略部分-->
table.render({
elem: '#test'
,url: 'json/default.json'
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,cols: [
[{
field: 'id',width: 80,title: 'ID',sort: true
}, {
field: 'username',width: 80,title: '用户名'
}, {
field: 'sex',width: 80,title: '性别'
}]
]
,response: {
statusName: 'status' //规定数据状态的字段名称,默认:code
,dataName: 'rows' //规定数据列表的字段名称,默认:data
}
});
<!-- 省略部分-->
这样,即使传过来的JSON中的参数名有问题,这样也能纠正过来。