我在 MySQL 中创建了一个用户表,我试图在使用 AJAX 单击表中的标题时对数据进行排序。
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'accounts';
$conn = new mysqli($host, $user, $pass, $db);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://kit.fontawesome.com/ce5233f2e0.js" crossorigin="anonymous"></script>\
<link rel="stylesheet" href="sort.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<title>Sort Users</title>
</head>
<body>
<div class="container" style="width:700px;" align="center">
<h3>Sort Users</h3><br>
<div class="table-responsive" id="employee_table">
<input type='hidden' id='sort' value='asc'>
<table width='100%' id='empTable' border='1' cellpadding='10'>
<tr>
<th><span onclick='sortTable("id")'>ID</span></th>
<th><span onclick='sortTable("username")'>Username</span></th>
<th><span onclick='sortTable("mail")'>Mail</span></th>
</tr>
<?php
$query = "SELECT * FROM users ORDER BY id ASC";
$result = mysqli_query($conn, $query);
while($row = mysqli_fetch_array($result))
{
?>
<tr>
<td><?php echo $row["id"];?></td>
<td><?php echo $row["username"];?></td>
<td><?php echo $row["mail"];?></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
<br>
<p>
<a href="home/index.php">Home</a>
</p>
</body>
</html>
<script>
function sortTable(column_name){
var sort = $("#sort").val();
$.ajax({
url:'query.php',
type:'post',
data:{column_name:column_name,sort:sort},
success: function(data){
$("#empTable").html(data);
if(sort == "asc"){
$("#sort").val("desc");
}else{
$("#sort").val("asc");
}
}
});
}
</script>
query.php文件:
<?php
include "sort.php";
$column_name = $_POST["column_name"];
$sort = $_POST["sort"];
$query = "SELECT * FROM users ORDER BY ".$column_name." ".$sort." ";
$result = mysqli_query($conn, $query);
$html = '';
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$username = $row['username'];
$mail = $row['mail'];
$html .= "<tr>
<td>".$id."</td>
<td>".$username."</td>
<td>".$mail."</td>
</tr>";
}
$html.= "</table>";
echo $html;
?>
排序有效,但它奇怪地复制了我的表并将排序后的数据写在一行中:
我没有看到任何人遇到与我相同的问题。我是初学者,请多关照 :)