layui中table展示后端數據
1.下載layui的資源文件
layui官網,下載解壓后就是下面圖里的文件
把layui整個文件夾引入項目
2.在項目里引入下載好的文件
3.啟動項目,在主頁發送一個ajax請求
<script>
var xhr = new XMLHttpRequest();
xhr.open("get","findAll");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send();
</script>
瀏覽器按F12查看請求
好,請求有發出去了,404先別管,主要是這個請求成功發出去了
4.接下來寫后台的代碼
數據庫
DAO
(我這里用了MyBatis,如果用原生的JDBC則自己寫流程)
@Repository
public interface BookDao {
@Select("select * from book")
List<Book> findAll();
}
Service
@Service
public class BookService {
@Autowired
private BookDao bookDao;
@Override
public List<Book> findAll() {
return bookDao.findAll();
}
}
去layui官網里把table的代碼看看
1.首先要在頁面引入layui的css及js
2.URL是數據的接口,並且layui只認json的數據格式,所以controller返回的數據就要是json格式
3.cols里的field是要跟數據庫查出來的列對應,只要后端返回的數據符合layui.table的格式,layui就會自動展示
所以我最終的頁面是這樣的
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>table模塊快速使用</title>
<link rel="stylesheet" href="layui/css/layui.css" media="all">
<script>
var xhr = new XMLHttpRequest();
xhr.open("get","findAll");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
xhr.send();
</script>
</head>
<body>
<script src="layui/layui.js"></script>
<table id="demo" lay-filter="test"></table>
<script>
layui.use('table', function(){
var table = layui.table;
//第一個實例
table.render({
elem: '#demo'
,url: '/findAll'
,cols: [[ //表頭
{field: 'id', title: 'ID', width:80,sort: true}
,{field: 'name', title: '書名', width:160}
,{field: 'price', title: '價格', width:80,sort: true}
]]
});
});
</script>
</body>
</html>
接下來編寫controller層的代碼
Controller
@Controller
@RequestMapping()
public class BookController {
@Autowired
private BookService bookService;
@RequestMapping(value="findAll",produces="text/html;charset=utf-8")
public @ResponseBody String findAll(){
List<Book> bookList = bookService.findAll();
String jsonString = JSON.toJSONString(bookList);
//下面這里這個格式是在網上找的
String books="{\"code\":\"0\",\"msg\":\"ok\",\"count\":100,\"data\":"+jsonString+"}";
System.out.println("-----"+books);
return books;
}
}
這樣我們就把json格式的數據返回去前端了
啟動項目,瀏覽器進入主頁
成功展示了。