2017-01-11 31 views
-2

我有一個代碼,它從數據庫中提取數據並使用jQuery顯示數據列表。我想在我的代碼中進行一些修改,即如果我單擊一個表頭,它應該按升序和降序切換列表。點擊桌面標題排序表與ajax

下面給出的是我的php代碼。

<html> 
<head> 
    <link rel="stylesheet" href="bootstrap/bootstrap-4.0.0-alpha.6-dist/css/bootstrap.min.css"> 
    <script src="bootstrap/jquery-3.1.1.min.js"></script> 
    <script src="bootstrap/bootstrap-4.0.0-alpha.6-dist/js/bootstrap.min.js"></script> 
</head> 
<body> 
<div class="container"> 
</div> 
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 
    <script id="source" language="javascript" type="text/javascript"> 
    $('#output').append("<br /><h3><center>Employee Table</center></h3>"); 
    // function explode(){ 
    $('#output').append("<input type='hidden' id='sort' value='asc'>"); 
    var html = "<br /><h1><center><b>Employee Table</b></center></h1>"; 
    $.ajax({          
    url: 'test2db.php', data: "", dataType: 'json', success: function(rows)  
     { 
     html+= "<div class='table-responsive'>"; 
     html+= "<table class='table table-bordered table-striped'>"; 
     html+= "<tr>" + 
        "<th>Employee Id</th>" + 
        "<th>Employee Name</th>" + 
        "<th>Email</th>" + 
        "<th>Message</th>" + 
        "<th>Date</th>" + 
       "</tr>" 
     for (var i in rows) 
     { 
      var row = rows[i]; 
      var employee_id = row[0]; 
      var employee_name = row[1]; 
      var email = row[2]; 
      var message = row[3]; 
      var date = row[4]; 
      html+= "<tr>" + 
        "<td width='25%'>" + employee_id + "</td>" + 
        "<td width='25%'>" + employee_name + "</td>" + 
        "<td width='25%'>" + email + "</td>" + 
        "<td width='25%'>" + message + "</td>" + 
        "<td width='25%'>" + date + "</td>" + 
       "</tr>";     
     } 
     html+= "</table>"; 
     html+= "</div>"; 
     $(".container").html(html); 
     } 
    }); 
</script> 
</body> 
</html> 

下面給出的是我的數據提取碼

<?php 
    mysql_connect("localhost", "root", "password") || die(mysql_error()); 
    mysql_select_db("emp") || die(mysql_error()); 
    $result = mysql_query("SELECT * FROM employee ORDER BY id DESC LIMIT 5"); 
    $data = array(); 
    while ($row = mysql_fetch_row($result)) 
    { 
    $data[] = $row; 
    } 
    echo json_encode($data); 
?> 
+0

「讓我的代碼適合我」?通過AJAX調用傳遞ASC或DESC,並更改您的select語句以反映相同。 – zerohero

+0

同一用戶提出的同一問題:[點擊表格標題時對動態數據進行升序或降序排序](http://stackoverflow.com/questions/41589257/sort-dynamic-data-ascending-or-descending-when-clicked-上表頭) –

回答

0

您可以使用Datatable Plugin來實現這一目標。

這是非常容易的,你可以添加更多的功能,如搜索,導入到CSV,PDF等到您的表(如果您需要)。

我強烈建議你使用Datatable Plugin