如何在DataTables中从文本文件加载JSON数据进行分页
我们对用于存储相关数据的HTML表格非常熟悉。DataTables是一个现代的jQuery插件,用于为我们的网页的HTML表格添加互动和高级控制。DataTables的一些功能是排序、搜索、分页和数据排序。有许多方法可以将数据输入DataTables。
在这篇文章中,我们将学习如何从一个文本文件中加载数据,这些数据可以用于分页或排序。
实现代码所需的预编译文件是
CSS:
https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css
//cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
示例:
<!DOCTYPE html>
<html>
<head>
<meta content="initial-scale=1, maximum-scale=1,
user-scalable=0" name="viewport" />
<meta name="viewport" content="width=device-width" />
<!--Datatable plugin CSS file -->
<link rel="stylesheet" href=
"https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css" />
<!--jQuery library file -->
<script type="text/javascript" src=
"https://code.jquery.com/jquery-3.5.1.js">
</script>
<!--Datatable plugin JS library file -->
<script type="text/javascript" src=
"https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js">
</script>
</head>
<body>
<h2>Datatables server side process</h2>
<!--HTML table with student data-->
<table id="tableID" class="display"
style="width: 100%;">
<thead>
<tr>
<th>StudentID</th>
<th>StudentName</th>
<th>Age</th>
<th>Gender</th>
<th>Marks Scored</th>
</tr>
</thead>
<tfoot>
<tr>
<th>StudentID</th>
<th>StudentName</th>
<th>Age</th>
<th>Gender</th>
<th>Marks Scored</th>
</tr>
</tfoot>
</table>
<script>
/* Initialization of datatable */
(document).ready(function () {
/* Student's data loaded from
text file */
('#tableID').DataTable({
"ajax": 'ajaxData.txt'
});
});
</script>
</body>
</html>
ajaxData.txt:以下是写在”ajaxData.txt”文件中的students表的数据,它被用于上述代码的JavaScript部分。
{
"data": [
[
"ST1",
"Preeti",
"35",
"Female",
"320"
],
[
"ST2",
"Vincy",
"36",
"Female",
"170"
],
[
"ST3",
"Ashwini",
"41",
"Female",
"860"
],
[
"ST4",
"Kelly",
"32",
"Female",
"433"
],
[
"ST5",
"Satvik",
"41",
"male",
"162"
],
[
"ST6",
"William",
"37",
"Female",
"372"
],
[
"ST7",
"Chandan",
"31",
"male",
"375"
],
[
"ST8",
"David",
"45",
"male",
"327"
],
[
"ST9",
"Harry",
"29",
"male",
"205"
],
[
"ST10",
"Frost",
"29",
"male",
"300"
],
[
"ST11",
"Ginny",
"31",
"male",
"560"
],
[
"ST12",
"Flod",
"45",
"Female",
"342"
],
[
"ST13",
"Marshy",
"23",
"Female",
"470"
],
[
"ST13",
"Kennedy",
"43",
"male",
"313"
],
[
"ST14",
"Fiza",
"31",
"Female",
"750"
],
[
"ST15",
"Silva",
"34",
"male",
"985"
]
]
}
输出:
从文件中加载的数据:
搜索和分页的执行: