Home >Web Front-end >Layui Tutorial >How to connect layui and backend
Layui front and backend data interaction:
layui has its own set of specific data format interactions (this is very important), and the code must be parameter :0, msg: "", count: data size (int), data: "Data List". Generally we choose to encapsulate and return the receiving class.
Layui frontend js request data
html code
<link rel="stylesheet" href="static/layui/css/layui.css" media="all" /> <script type="text/javascript" src="static/layui/layui.js"></script> <table class="layui-hide" id="test" lay-filter="table"></table>
js code
layui.use(['form','layer','table'], function(){ var table = layui.table ,form = layui.form,$=layui.$; table.render({ elem: '#test' //绑定table id ,url:'sys/menu/list' //数据请求路径 ,cellMinWidth: 80 ,cols: [[ {type:'numbers'} ,{field:'name', title:'菜单名称'} ,{field:'parentName', title:'父菜单名称',width:150} ,{field:'url', title: '菜单路径'} ,{field:'perms', title: '菜单权限'} ,{field:'type', title:'类型'} ,{field:'icon', title:'图标'} ,{field:'orderNum', title:'排序'} ,{fixed: 'right',title: '操作', width:180, align:'center', toolbar: '#toolBar'}//一个工具栏 具体请查看layui官网 ]] ,page: true //开启分页 ,limit:10 //默认十条数据一页 ,limits:[10,20,30,50] //数据分页条 ,id: 'testReload' }); });
java backend code
@RequestMapping("/list") @ResponseBody @RequiresPermissions("sys:menu:list") public Layui list(@RequestParam Map<String, Object> params){ //查询列表数据 Query query = new Query(params); List<SysMenuEntity> menuList = sysMenuService.queryList(query); int total = sysMenuService.queryTotal(query); PageUtils pageUtil = new PageUtils(menuList, total, query.getLimit(), query.getPage()); return Layui.data(pageUtil.getTotalCount(), pageUtil.getList()); }
Layui tool class code
public class Layui extends HashMap<String, Object> { public static Layui data(Integer count,List<?> data){ Layui r = new Layui(); r.put("code", 0); r.put("msg", ""); r.put("count", count); r.put("data", data); return r; } }
PageUtils is optional here, you can encapsulate it yourself
@Data public class PageUtils implements Serializable { private static final long serialVersionUID = -1202716581589799959L; //总记录数 private int totalCount; //每页记录数 private int pageSize; //总页数 private int totalPage; //当前页数 private int currPage; //列表数据 private List<?> list; /** * 分页 * @param list 列表数据 * @param totalCount 总记录数 * @param pageSize 每页记录数 * @param currPage 当前页数 */ public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) { this.list = list; this.totalCount = totalCount; this.pageSize = pageSize; this.currPage = currPage; this.totalPage = (int)Math.ceil((double)totalCount/pageSize); } }
Recommendation: layui framework tutorial
The above is the detailed content of How to connect layui and backend. For more information, please follow other related articles on the PHP Chinese website!