使用 ajax 更新页面数据

update the page data using ajax

如果我点击书籍 link 他会按升序排列书籍,如果我再次点击他会按降序排列,但他不会执行此操作,除非我点击下一个或上一个提交,为什么他没有点击下一个或上一个就没有更新页面?

$(document).ready(function() {
$("#sorter").click(function(e) {
e.preventDefault();
var order_by_value = $('input[name="order_by"]').val();
    $.ajax({
      type: 'GET',
       url: "" + 'http://test.local/UUser.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');
    }
   });
});
});

这是我的职能

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);

 }

此事件正在侦听带有 Id 排序器的元素,因此它可以正常工作,您只需要将服务器的答案显示给客户端即可

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');
     //here you display the result from the server
    $("#myTable").html(res);
    }

仅从 AJAX 函数本身很难判断。逻辑似乎没问题。也许您没有针对特定元素,或者 HTML 代码的结构对于您要实现的目标存在一些逻辑缺陷?