2016-03-15 65 views
0

如何使用AJAX對從數據庫中顯示的表進行排序? 我見過幾個例子,但是他們的MVC和我正在做的完全不一樣,我完全迷失了。有人可以爲此提供一些有用的資源嗎?謝謝。這是我的代碼。使用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; 
} 

回答

0

您可以遵循這些簡單的步驟:

  • th(CustomerID,FirstName,...)添加javascript偵聽器。當此元素上的用戶點擊您創建的特殊的URL的AJAX調用獲取數據
  • 添加URL獲取數據,I,E /getCustomers?OrderByColumn=CustomerID&OrderDirection=Desc其中OrderByColumn排序定義列和OrderDirection在簡單的情況下,該網址會檢索所有定義方向
  • HTML表,你只需更換舊錶新
  • 在更復雜的情況下,該網址將檢索與數據JSON和您與您的JS代碼處理它
+0

感謝,這一切纔有意義。我在th標籤上使用onclick事件。我只是不知道如何實現ajax等。我已經展示的所有東西是如何使用按鈕使ajax顯示某些東西。 – lukas13x