博客列表 >php+jquery实现无刷新分页和前端端交互操作数据库

php+jquery实现无刷新分页和前端端交互操作数据库

咸鱼老爷
咸鱼老爷原创
2021年03月27日 14:40:33686浏览

后端php查询所有数据,前端通过ajax请求获取并且动态生成带有分页的表格
前端html代码

  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  8. <title>Document</title>
  9. <style>
  10. .active{
  11. color: green;
  12. }
  13. .modal{
  14. width: 550px;
  15. position: absolute;
  16. top: 0;
  17. background-color: skyblue;
  18. display: none;
  19. }
  20. a{
  21. text-decoration: none;
  22. color: #000;
  23. }
  24. </style>
  25. </head>
  26. <body>
  27. <table>
  28. <caption>员工列表</caption>
  29. <thead>
  30. <tr>
  31. <th>id</th>
  32. <th>姓名</th>
  33. <th>性别</th>
  34. <th>年龄</th>
  35. <th>邮箱</th>
  36. <th>生日</th>
  37. <th>入职日期</th>
  38. <th>操作</th>
  39. </tr>
  40. </thead>
  41. <tbody>
  42. </tbody>
  43. </table>
  44. <p class="page">
  45. </p>
  46. <div class="modal">
  47. <button class="close">关闭</button>
  48. <form action="" method="POST" id="edit">
  49. <p><label for="">姓名:<input type="text" value="" name="name" id="name" /></label></p>
  50. <p><label for="">性别:<select name="gender" id="gender">
  51. <option value="male"></option>
  52. <option value="female"></option>
  53. </select>
  54. </label></p>
  55. <p> <label for="">年龄:<input type="text" value="" name="age" id="age" /></label></p>
  56. <p><label for="">邮箱:<input type="email" value="" name="email" id="email" /></label></p>
  57. <p><label for="">生日:<input type="text" value="" name="borthday" id="borthday" /></label></p>
  58. <input type="hidden" value="" name="id" id="id" />
  59. <p> <label for=""><button class="save">保存</button></label></p>
  60. </form>
  61. </div>
  62. </body>
  63. <script>
  64. select(1);
  65. function show(data) {
  66. var html = '';
  67. $.each(data, function(index, value) {
  68. html += '<tr>';
  69. html += '<td>' + data[index]['id'] + '</td>';
  70. html += '<td>' + data[index]['name'] + '</td>';
  71. html += '<td>' + data[index]['gender'] + '</td>';
  72. html += '<td>' + data[index]['age'] + '</td>';
  73. html += '<td>' + data[index]['email'] + '</td>';
  74. html += '<td>' + data[index]['borthday'] + '</td>';
  75. html += '<td>' + data[index]['create_time'] + '</td>';
  76. html += '<td><button class="edit" data-index='+data[index]['id']+'>编辑</button><button class="del"data-index='+data[index]['id']+'>删除</button></td>';
  77. html += '</tr>';
  78. })
  79. return html;
  80. }
  81. // 查询
  82. function select(page = 1) {
  83. $.get("http://127.0.0.119/pdo/limit.php?action=select&p=" + page, function(res) {
  84. var obj = jQuery.parseJSON(res);
  85. let pages = obj.pages;
  86. let rows = obj.rows;
  87. console.log(rows);
  88. $('tbody').html(show(rows));
  89. $('.page').html(getPage(page, pages));
  90. })
  91. }
  92. function getPage(page = 1, pages) {
  93. let p = "";
  94. let active = "";
  95. // 首页|上一页
  96. if (page <= 1) page = 1;
  97. if (page !== 1) {
  98. p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=1">首页</a>';
  99. p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p= '+ Math.max(1, page - 1) + '">上一页</a>';
  100. }
  101. // 高亮
  102. for (i = 1; i <= pages; i++) {
  103. active = "";
  104. if (page == i) active = 'class="active"';
  105. p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + i+ '"'+ active + '>' + i + '</a>';
  106. }
  107. // 下一页|尾页
  108. if (page >= pages) page = pages;
  109. if (page != pages) {
  110. p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + ( parseInt(page) +1 ) + '">下一页</a>';
  111. p += '<a href="http://127.0.0.119/pdo/limit.php?action=select&p=' + pages + '">尾页</a>';
  112. }
  113. return p;
  114. }
  115. $('.page').on('click',
  116. function(event){
  117. event.preventDefault();
  118. event.stopPropagation();
  119. let page=$(event.target).attr('href');
  120. page=page.split('=')[2];
  121. select(page);
  122. }
  123. );
  124. //编辑
  125. $(' tbody').on('click','.edit',function(){
  126. let id=$(this).attr('data-index');
  127. $.get("http://127.0.0.119/pdo/limit.php?action=getOne&id=" + id, function(res) {
  128. var obj = jQuery.parseJSON(res);
  129. let rows = obj.rows;
  130. let name=rows.name;
  131. let gender=rows.gender;
  132. let age=rows.age;
  133. let email=rows.email;
  134. let borthday=rows.borthday;
  135. let id=rows.id;
  136. $('#name').val(name);
  137. if (gender=='male'){
  138. $('#gender option').removeAttr('selected');
  139. $('#gender option:nth-of-type(0)').attr('selected',true);
  140. }else{
  141. $('#gender option').removeAttr('selected');
  142. $('#gender option:nth-of-type(2)').attr('selected',true);
  143. }
  144. $('#age').val(age);
  145. $('#email').val(email);
  146. $('#borthday').val(borthday);
  147. $('#id').val(id);
  148. $('.modal').show();
  149. });
  150. });
  151. $('.close').click(()=>{
  152. $('.modal').hide();
  153. })
  154. //保存
  155. $('.save').on('click',function(event){
  156. event.preventDefault();
  157. $.post("http://127.0.0.119/pdo/limit.php?action=save", $("#edit").serialize(),function(data){
  158. alert(data);
  159. $('.modal').hide();
  160. location.reload();
  161. });
  162. })
  163. //删除
  164. $(' tbody').on('click','.del',function(){
  165. let id=$(this).attr('data-index');
  166. $.get("http://127.0.0.119/pdo/limit.php?action=delete&id=" + id, function(res) {
  167. location.reload();
  168. alert(res);
  169. });
  170. });
  171. </script>
  172. </html>

后端php代码

  1. $config = [
  2. 'type' => 'mysql',
  3. 'host' => '127.0.0.1',
  4. 'dbname' => 'php',
  5. 'port' => 3306,
  6. 'charset' => 'utf8mb4',
  7. 'username' => 'root',
  8. 'passwrod' => '123456',
  9. ];
  10. extract($config);
  11. $dsn = sprintf('%s:dbname=%s;', $type, $dbname);
  12. try {
  13. $pdo = new PDO($dsn, $username, $passwrod);
  14. //设置结果集的返回类型
  15. $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
  16. } catch (PDOException $e) {
  17. die('连接失败' . $e->getMessage());
  18. }
  19. //计算共计多少页?
  20. $action = $_GET['action'] ?? 'select';
  21. $page = $_GET['p'] ?? 1;
  22. $id = $_GET['id'] ?? 1;
  23. $data = $_POST;
  24. switch ($action) {
  25. case 'select':
  26. select($pdo, $page);
  27. break;
  28. case 'getOne':
  29. getOne($pdo, $id);
  30. break;
  31. case 'save':
  32. save($pdo, $data);
  33. break;
  34. case 'delete':
  35. delete($pdo, $id);
  36. break;
  37. }
  38. //查询所有数据
  39. function select($pdo, $page = 1, $num = 5)
  40. {
  41. //计算当前页的起始偏移量
  42. $offset = ($page - 1) * $num;
  43. //ceil()向上取整
  44. $sql = "SELECT CEIL(COUNT(1)/{$num}) total FROM user";
  45. $row = $pdo->query($sql);
  46. $pages = $row->fetch()['total'];
  47. // print_r($row);
  48. //每页显示的数据
  49. $sql = "SELECT * FROM `user` LIMIT {$offset},{$num}";
  50. $stmt = $pdo->prepare($sql);
  51. $stmt->execute();
  52. $rows = $stmt->fetchAll();
  53. echo json_encode(['pages' => $pages, 'rows' => $rows]);
  54. }
  55. //获取单条信息
  56. function getOne($pdo, $id)
  57. {
  58. $sql = "SELECT * FROM user WHERE id={$id}";
  59. $stmt = $pdo->prepare($sql);
  60. $stmt->execute();
  61. $rows = $stmt->fetch();
  62. echo json_encode(['rows' => $rows]);
  63. }
  64. //更新数据
  65. function save($pdo, $data)
  66. {
  67. $sql = "UPDATE `user` SET name = :name, gender = :gender, age = :age, email = :email, borthday = :borthday WHERE id=:id";
  68. $stmt = $pdo->prepare($sql);
  69. $stmt->bindParam(':name', $data['name'], PDO::PARAM_STR);
  70. $stmt->bindParam(':gender', $data['gender'], PDO::PARAM_STR);
  71. $stmt->bindParam(':age', $data['age'], PDO::PARAM_STR);
  72. $stmt->bindParam(':email', $data['email'], PDO::PARAM_STR);
  73. $stmt->bindParam(':borthday', $data['borthday'], PDO::PARAM_STR);
  74. $stmt->bindParam(':id', $data['id'], PDO::PARAM_INT);
  75. $stmt->execute();
  76. if ($stmt->rowCount() > 0) {
  77. echo '更新成功';
  78. } else {
  79. echo '更新失败';
  80. }
  81. }
  82. //删除数据
  83. function delete($pdo, $id)
  84. {
  85. $sql = "DELETE FROM `user` WHERE id=:id";
  86. $stmt = $pdo->prepare($sql);
  87. $stmt->bindParam(':id', $id, PDO::PARAM_INT);
  88. $stmt->execute();
  89. if ($stmt->rowCount() > 0) {
  90. echo '删除成功';
  91. } else {
  92. echo '删除失败';
  93. }
  94. }

效果图

声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议