PHP ajax+jQuery 实现批量删除功能实例代码小结
程序员文章站
2022-10-04 16:52:38
目录结构
piliangshan.php
目录结构
piliangshan.php
<?php require_once './db_conn.php'; $sql = "select * from user"; $result = mysqli_query($conn, $sql); ?> <html lang="zh-cn"> <head> <meta charset="utf-8"> <title>全选演示</title> <meta http-equiv="x-ua-compatible" content="ie=edge"> <link rel="stylesheet" type="text/css" href="./static/bootstrap.min.css" rel="external nofollow" > <script src="./static/jquery.js"></script> <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0"> </head> <body> <form enctype="multipart/form-data" method="post"> <div class="bs-example" data-example-id="simple-table" style="padding-left: 30px;"> <table class="table" id="j-dl"> <a href="javascript:void(0);" rel="external nofollow" class="btn btn-danger" onclick="selectall()" title="删除选定数据" style="font-weight:normal">批量删除</a> <thead> <tr> <th><input type="checkbox" id="j-all" class="ckb"></th> <th>first name</th> <th>last name</th> <th>username</th> </tr> </thead> <tbody> <?php while ($row = mysqli_fetch_array($result, mysqli_assoc)) { echo '<tr> <th><input type="checkbox" class="ck" id="ck-1" value="'.$row['id'].'"></th> <th scope="row">'.$row['id'].'</th> <td>'.$row['username'].'</td> <td>'.$row['sort'].'</td> </tr>'; } ?> </tbody> </table> </div> </form> <script> (function () { var $all = $('#j-all'); var $dl = $('#j-dl'); // 绑定全选按钮点击事件,让下面所有的复选框是跟全选的一样 $all.on('click', function () { $dl.find('.ck').prop('checked', !!this.checked); }); // 绑定点击所有的复选框,点击的时候判断是否页面中全选了 $dl.find('.ck').on('click', function () { // 我只是喜欢用filter(fn),用选择器也行 // 查找没有选择的元素 var $unselectedelem = $dl.find('.ck').filter(function () { return !this.checked; }); // 如果有没有选中的,则让全选的取消 if ($unselectedelem.length) { $all.prop('checked', false); } else { $all.prop('checked', true); } }); })(); </script> <script type="text/javascript"> function selectall() { var ids = ''; $(".ck").each(function() { if ($(this).is(':checked')) { ids += ',' + $(this).val(); //逐个获取id值,并用逗号分割开 } }); ids = ids.substring(1); // 进行id处理,去除第一位的逗号 if (ids.length == 0) { alert('请至少选择一项'); } else { if (confirm("确定删除选中的?")) { $.ajax({ type: "post", url: "piliangdo.php", data: { ids:ids }, success: function(data) { if(data.trim()=="yes") { alert("删除成功"); location.reload() //刷新页面 } else { alert("删除失败"); } } }); } } } </script> </body> </html>
piliangdo.php
<?php header("content-type:text/html;charset='utf-8'"); require_once './db_conn.php'; $ids = trim($_post['ids']); $ids = explode(',', $ids); foreach ($ids as $key => $val) { $del_sql = "delete from `user` where id = '$val'"; $result = mysqli_query($conn, $del_sql); } if ($result) { echo "yes"; } else{ echo "no"; } ?>
总结
以上所述是小编给大家介绍的php ajax+jquery 实现批量删除功能实例代码小结,希望对大家有所帮助