动态扩展和折叠表格行

时间:2019-10-26 13:30:23

标签: javascript jquery ajax bootstrap-4

我正在尝试实现一个引导表,当用户单击第一列上的按钮时,该表就会展开,并显示更多详细信息。

作为参考,我正在尝试实现类似于以下的功能:

https://datatables.net/examples/server_side/row_details.html

但是,我不打算使用DataTables框架。

该表不应包含页面加载时所有行的详细信息。基本上,当单击按钮时,我希望发送ajax请求(使用beforeSend函数将显示ajax加载屏幕),并且当成功执行ajax函数时,应使用通过ajax获取的详细信息扩展特定行,当然加载屏幕叠加层将被隐藏)。然后,当与扩展行相关的按钮被单击时,该行应折叠。

我只是在寻找此实施的入门指南。

你们能帮我吗?

1 个答案:

答案 0 :(得分:0)

这是一个很好的问题!我很乐意为您提供帮助。

第一-一个XML文件(database.xml),用于从中调用您的信息(必要时展开):

<?xml version = '1.0' encoding='utf-8' ?>
<database>
   <row id = '1'>
      <user>
          <name>Bob</name>
          <joined>10-10-2019</joined>
      </user>
   </row>
   <row id = '2'>
      <user>
          <name>Fred</name>
          <joined>10-11-2019</joined>
      </user>
   </row>
</database>

第二-带有表(index.php)的php文件:

<html>
   <head>
   </head>
   <body>
      <table>
          <?
          $users = simplexml_load_file('database.xml');
          foreach ($users-row) as $row {
             echo '<tr class = "row '.$row['id'].'">'
             echo '<td class = "expand"><div role = "button" class = "expand-button '.$row['id'].'">Expand</div></td>'
             echo '<td class = "username">'.$row->name.'</td>';
             echo '</tr>';
          }
          ?>
      </table>
   </body>
</html>

第三-具有XMLHTTPRequest的JavaScript文件,用于调用php文件(app.js):

const getClass = (c) => document.getElementsByClassName(c);
for (let i = 0; i < getClass('expand-button').length; i++) {
   getClass('expand-button')[i].addEventListener('click', expand, false);
}
function expand(e) {
   let xhr = new XMLHTTPRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
         getClass('row '+e.target.className.split(' ')[1]).innerHTML += xhr.responseText;
      }
   };
   xhr.open('GET', 'retrieveUsers.php?rowId='+e.target.parentElement.className.split(' ')[1], true);
   xhr.send();
}

第四-(最后!)php文件来处理请求:

<?
$rowId = $_GET['rowId'];
$users = simplexml_load_file('database.xml');
foreach ($users-row) as $row {
   if ($row['id'] === $rowId) {
      echo '<tr class = "expanded">';
      echo 'Username: '.$row->name;
      echo '<br />Joined: '.$row->joined;
      echo '</tr>';
   }
}
?>

告诉我这是否可行