【问题标题】:Using Ajax to sort a table in MVC architecture在 MVC 架构中使用 Ajax 对表进行排序
【发布时间】:2016-03-15 17:44:52
【问题描述】:

如何使用 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>

Index.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;
}

【问题讨论】:

    标签: php ajax model-view-controller


    【解决方案1】:

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

    • th (CustomerID, FirstName, ...) 添加 javascript 监听器。当用户单击此元素时,您会创建对特殊 url 的 ajax 调用以获取数据
    • 添加获取数据的url,即/getCustomers?OrderByColumn=CustomerID&amp;OrderDirection=Desc,其中OrderByColumn定义排序列,OrderDirection定义方向
    • 在简单的情况下,此 url 将检索所有 html 表,您只需将旧表替换为新表
    • 在更复杂的情况下,此 url 将检索带有数据的 json,然后您使用 js 代码对其进行处理

    【讨论】:

    • 谢谢,这一切都说得通。我在 th 标签上使用 onclick 事件。我只是不知道如何实现 ajax 等。我所看到的只是如何使用按钮使用 ajax 使某些东西出现。
    猜你喜欢
    • 2016-03-04
    • 2016-03-30
    • 2011-01-03
    • 2016-03-02
    • 2010-10-19
    • 2020-10-07
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多