利用bootstrap table表格将后端接口数据展示在表格中

利用bootstrap table表格将后端接口数据展示在表格中


首先展示项目案例:
表格中表头是在html中写死,其余的数据都是对应表头加载出来的。

利用bootstrap table表格将后端接口数据展示在表格中
bootstrap表格后端接受数据案例

 

下图为模拟出来的后端传的数据,数据中的key值需要与写死在表头中的data-field一一对应:

利用bootstrap table表格将后端接口数据展示在表格中
加载数据内容打印

 

下面是所有完整的代码,重点以及主要的解释已经在代码内进行注释:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
//此处引入bootstrap css文件
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
//此处引入bootstrap table css文件
    <link href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css" rel="stylesheet">
</head>
<body>
<table class="table table-condensed"
          id="table"
          data-toggle="table"
          data-toolbar="#toolbar"
          data-height="400"
          data-search="true" >
          <thead class="thead-light">
            <tr>
              <th data-field="id">ID</th>
              <th data-field="name">Item Name</th>
              <th data-field="price">Item Price</th>
              <th data-field="price1">Item Price</th>
              <th data-field="price2">Item Price</th>
              <th data-field="price3">Item Price</th>
            </tr>
          </thead>
        </table>
//此处引入jquery文件,此文件在本地,需自行下载引入
        <script src="./js/jquery-1.12.4.min.js"></script>
//此处需引入bootstrap table 的js文件
        <script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>
        <script>
        // 此处方法模拟打印随机后端数据,打印的结构见上面,加载数据内容打印
          function randomData() {
                var startId = ~~(Math.random() * 100)
                var rows = []
                for (var i = 0; i < 10; i++) {
                    rows.push({
                        id: startId + i,
                        name: 'test' + (startId + i),
                        price: '$' + (startId + i),
                        price1: '$' + (startId + i),
                        price2: '$' + (startId + i),
                        price3: '$' + (startId + i)
                    })
                }
                console.log(rows)
                return rows;
            }

            
          $(function() {
            // 核心内容,bootstrapTable自带方法,将randomdata中的数据加载如表格中,数据中的key值需要与写死在表头中的data-field一一对应
            $('#table').bootstrapTable('append',randomData())
            // 下面一行代码是在表格中增加样式,让所有内容居中
              $("td,th").addClass("text-center");
          })
        </script>
</body>
</html>