layui根据后台接口渲染数据,数据始终渲染不上去
页面:
<%--
Created by IntelliJ IDEA.
User: waper
Date: 2020/8/17
Time: 17:25
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="static/layui/css/layui.css">
</head>
<body>
<table id="demo" lay-filter="test"></table>
<script src="static/jquery-3.5.1.js"></script>
<script src="static/layui/layui.js"></script>
<script type="text/javascript">
$(function (){
// $.ajax({
// url:"http://localhost:8888/waper/api/hero/test",
// method:"get",
// data:"data",
// success: function(result){
// console.log(result)
// }
// })
})
layui.use('table', function(){
var table = layui.table;
//第一个实例
table.render({
elem: '#demo'
,height: 900
,url: 'http://localhost:8888/waper/api/hero/test' //数据接口
,page: true //开启分页
,dataType:"application/json"
,cols: [[ //表头
{field: 'ename', title: '英雄id', width:100, sort: true ,align: 'center'}
,{field: 'cname', title: '英雄名称', width:150 ,align: 'center'}
,{field: 'title', title: '标题', width:150, sort: true ,align: 'center'}
,{field: 'pay_type', title: '支付类型', width:100 ,align: 'center'}
,{field: 'new_type', title: '类型', width: 80 ,align: 'center'}
,{field: 'hero_type', title: '英雄职业', width: 100, sort: true ,align: 'center'}
,{field: 'hero_type2', title: '英雄职业二', width: 130, sort: true ,align: 'center'}
,{field: 'skin_name', title: '皮肤名称', width: 500 ,align: 'center'}
]],
limit:20, limits: [1, 2, 3,4]
,parseData : function (res){
let str= [{
"ename": 533,
"cname": "阿古朵",
"title": "山林之子",
"new_type": 1,
"hero_type": 3,
"skin_name": "山林之子"}]
console.log("后台数据"+res.data)
console.log(typeof res.data)
console.log("写死数据"+res.data)
console.log(typeof str)
return {
"code": 0, //解析接口状态
"msg": "fuckyou", //解析提示文本
"data":res.data,//解析数据列表
"count": 1000
}
}
});
});
</script>
</body>
</html>
后台请求响应的数据
data:
让我看看官网文档,异步接口如何处理的:官网地址
以下摘自官网文档里:
官网
具体位子在:数据表格 ==> 异步数据接口 ===> parseData
默认规定的数据格式
数据格式解析的回调函数,用于将返回的任意数据格式解析成 table 组件规定的数据格式。
table 组件默认规定的数据格式为(参考:/demo/table/user/):
{
"code": 0,
"msg": "",
"count": 1000,
"data": [{}, {}] // list里面是对象
}
很多时候,您接口返回的数据格式并不一定都符合 table 默认规定的格式,比如:
假设您返回的数据格式:
{
"status": 0,
"message": "",
"total": 180,
"data": {
"item": [{}, {}]
}
}
那么你需要借助 parseData 回调函数将其解析成 table 组件所规定的数据格式
```java
table.render({
elem: '#demp'
,url: ''
,parseData: function(res){ //res 即为原始返回的数据
return {
"code": res.status, //解析接口状态
"msg": res.message, //解析提示文本
"count": res.total, //解析数据长度
"data": res.data.item //解析数据列表
};
}
//,…… //其他参数
});
如果你的接口返回的数据里面如果是json字符串的话,要转成json,不然渲染不出数据: