【归纳】Layui table.render里的json后台传入
在使用Layui的table元素时,传入的json的数据格式是有其自身定义的,需要另外添加一些字符,以正确传入。
为了传入符合前端格式的数据:
table.render({
elem: '#test'
,url:'http://localhost:8080/pictures'
,toolbar: '#toolbarDemo' //开启头部工具栏,并为其绑定左侧模板
,defaultToolbar: ['filter', 'exports', 'print', { //自定义头部工具栏右侧图标。如无需自定义,去除该参数即可
title: '提示'
,layEvent: 'LAYTABLE_TIPS'
,icon: 'layui-icon-tips'
}]
,title: '用户数据表'
,cols: [
[
{type: 'checkbox', fixed: 'left'}
,{field: 'id', title: 'ID', width:80, sort: true, fixed: 'left', totalRowText: '合计:'}
,{field: 'picname', title: '名字', width:200}
,{field: 'character', title: '属性', width:150}
,{field: 'home', title: '栖息地', width: 200}
,{field: 'url', title: 'url', width: 300}
,{fixed: 'right', title: '操作',width: 165, align:'center', toolbar: '#barDemo'}
]
]
,page: true
});
在entity层,使用了transient 修饰符对字段进行限定:
@Data @AllArgsConstructor @NoArgsConstructor @Entity(name="picture") public class Picture { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "picname") private String picname; @Column(name = "type") private transient String type; @Column(name = "url") private String url; @Column(name = "userid") private transient Long userid; @Column(name = "englishname") private transient String englishname; @Column(name = "character") private String character; @Column(name = "home") private String home; }
在传入中,为了满足Layui的格式要求,加上了一些头部:code、msg、count、data
@RequestMapping("pictures") public String getPictures(HttpSession session){ User user=(User)session.getAttribute("user"); Long userid=user.getId(); List<Picture> pictures; if(userid==1) pictures=picService.getAllPicture(); else pictures=picMapper.getPicbyUserid(userid); String picstring=gson.toJson(pictures); log.info(" 序列化结果:" + "{ \"code\": 0, \"msg\": \"\",\"count\": 15,\"data\": "+picstring+"}"); picstring="{ \"code\": 0, \"msg\": \"\",\"count\": 10,\"data\": "+picstring+"}"; return picstring; }
最终成功传入,显示:
from Chu