当我点击图书链接时,它应该按升序对图书进行排序,如果我再次点击它应该按降序排序。 为什么当我在第一页并点击书籍链接时,它会对书籍进行排序,但只有当我点击两次时,例如我在第二页上点击链接时,排序已执行,但它将我返回到第一页。为什么?
这是我在index.php中的ajax代码
$(document).ready(function() {
$("#sorter").click(function() {
// e.preventDefault();
var order_by_value = $('input[name="order_by"]').val();
$.ajax({
type: 'GET',
url: "" + 'http://test.local/ajax-data.php?action=getBooks',
data:{
'order_by_value': order_by_value,
//button: 'button',
},
success: function (res) {
console.log(res);
if(order_by_value == "ASC"){
$('input[name="order_by"]').val("DESC");
} else {
$('input[name="order_by"]').val("ASC");
}
// $('input[name="current"]').trigger('click');
// display the result from the server
$("#myTable").html(res);
}
});
});
});
这是我在UUser.php中获取图书的功能
public function getBooks($start = 0, $limit = 2, $order = "ASC")
{
$sql_start = $start * $limit;
$sql_limit = $limit;
$sql_order_by = $order;
$query = "SELECT Library.nameOfBook, userBook.book_id, userBook.user_id FROM loginUser JOIN userBook JOIN Library ON userBook.user_id = loginUser.id AND userBook.book_id = Library.id WHERE loginUser.username=:username ORDER BY Library.nameOfBook $sql_order_by LIMIT $sql_start, $sql_limit";
$statment = $this->db->prepare($query);
$statment->execute([
':username' => $this->username
]);
$result = $statment->fetchAll();
echo "<table id='myTable' border='1'>
<tr>
<th><a id='sorter' href='#'>Books</a></th>
<th>Action</th>
</tr>";
foreach($result as $row){
echo "<tr>";
echo "<td>" . $row['nameOfBook'] . "</td>";
echo "<td>" ."<input type='submit' id='delete".$row['book_id']."-".$row['user_id']."' onclick='deleteBook(this)' name='delete' value='Delete'>" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "";
return count($result);
}
这是ajax称之为
的文件<?php
include_once('UUser.php');
if(isset($_GET['action']) )
{
$object = new User();
switch($_GET['action'])
{
case "getBooks":
$object->setUserName($_SESSION['username']);
$object->getBooks();
break;
default:
echo('there is no action');
break;
}
}
?>