2017-01-11 7 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> 

下記のあなたはこれを達成するためにDatatable Pluginを使用することができます私のデータの抽出コード

<?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

です。

非常に簡単で、検索、csv、pdfなどへのインポートなどの機能をテーブルに追加することができます(必要な場合)。

私は強く、上記のリンク上のロジックを参照し、それを使用Datatable Plugin

関連する問題