使用 Ajax 对 MVC 体系结构中的表进行排序


Using Ajax to sort a table in MVC architecture

如何使用 AJAX 对数据库中显示的表进行排序?我看过一些例子,但他们的MVC与我正在做的事情完全不同,我很迷茫。有人可以为此提供一些有用的资源吗?谢谢。这是我的代码。

表格视图

<table>
<thead>
<tr>
    <th>CustomerID</th>
    <th>FirstName</th>
    <th>LastName</th>
    <th>Address</th>
    <th>Street</th>
    <th>County</th>
    <th>Mobile</th>
    <th>Email</th>
</tr>
</thead>
<?php foreach ($customers as $customer) : ?>
    <tbody>
    <tr>
        <td><?php echo $customer['customerID']; ?></td>
        <td><?php echo $customer['fname']; ?></td>
        <td><?php echo $customer['lname']; ?></td>
        <td><?php echo $customer['address']; ?></td>
        <td><?php echo $customer['street']; ?></td>
        <td><?php echo $customer['county']; ?></td>
        <td><?php echo $customer['mobile']; ?></td>
        <td><?php echo $customer['email']; ?></td>
    </tr>
    </tbody>
<?php endforeach; ?>
</table>

索引.php操作调用

if ($action == 'view_customers') {
// call functions from the MODEL to get data from DB
$customers = get_customers();

include('./view/view_customers.php');
} 

模型

function get_customers(){
    global $db;
    $query = 'SELECT * FROM customers';
    $statement = $db->prepare($query);
    $statement->execute();
    return $statement;
}

您可以按照以下简单步骤操作:

  • th添加 JavaScript 侦听器(CustomerID、FirstName, ...)。当用户单击此元素时,您可以创建对特殊 url 的 ajax 调用以获取数据
  • 添加用于获取数据的 url,即 /getCustomers?OrderByColumn=CustomerID&OrderDirection=Desc 其中 OrderByColumn 定义用于排序的列和 OrderDirection 定义方向
  • 在简单的情况下,此URL将检索所有HTML表,您只需用新表替换旧表即可
  • 在更复杂的情况下,此 URL 将检索包含数据的 JSON,并使用 JS 代码处理它