1. 程式人生 > >ajax全選、全不選、反選、單刪/批刪

ajax全選、全不選、反選、單刪/批刪

UNC soc query select pre inpu HR delete 查詢

show.php

<meta charset="utf-8">
<?php
//鏈接數據庫
$link = mysqli_connect(‘127.0.0.1‘,‘root‘,‘root‘,‘mone‘);
//設置字符集
mysqli_query($link,‘set names utf8‘);


//接收當前頁
$page = empty($_GET[‘page‘])?1:$_GET[‘page‘];
//求出總條數
$sql = "select * from user";
$res = mysqli_query($link,$sql);
$count = mysqli_num_rows
($res); //每頁顯示多少條 $length = 3; //求出總頁數 $num_page = ceil($count/$length); //偏移量 $limit = ($page-1)*$length; //查詢 $sql2 = "select * from user limit $limit,$length"; $res2 = mysqli_query($link,$sql2); while($a=mysqli_fetch_assoc($res2)){ $data[‘data‘][] = $a; } $data[‘home_page‘] = 1; $data[‘prev_page‘] = $page
-1<1?1:$page-1; $data[‘next_page‘] = $page+1>$num_page?$num_page:$page+1; $data[‘last_page‘] = $num_page; ?> <table> <tr> <th>選擇</th> <th>ID</th> <th>用戶名</th> <th>密碼</th> <th>性別</th> <th>年齡</th> <th>班級</th> <th>手機</th> <th>編輯</th> </tr> <div id="main"> <?php foreach
($data[‘data‘] as $k=>$v){ ?> <tr id="<?php echo $v[‘user_id‘];?>"> <td><input type="checkbox" name="check" value="<?php echo $v[‘user_id‘];?>"></td> <td><?php echo $v[‘user_id‘];?></td> <td><?php echo $v[‘username‘];?></td> <td><?php echo $v[‘pwd‘];?></td> <td><?php echo $v[‘sex‘];?></td> <td><?php echo $v[‘age‘];?></td> <td><?php echo $v[‘class_name‘];?></td> <td><?php echo $v[‘phone‘];?></td> <td> <a href="">修改</a> </td> </tr> <?php } ?> </div> </table> <button onclick="fun1()">全選</button> <button onclick="fun2()">全不選</button> <button onclick="fun3()">反選</button> <button onclick="fun4()">單刪/批刪</button> <script> function fun1(){ var check = document.getElementsByName(‘check‘); for(var i=0;i<check.length;i++){ if(check[i].checked==false){ check[i].checked=true; } } } function fun2(){ var check = document.getElementsByName(‘check‘); for(var i=0;i<check.length;i++){ if(check[i].checked==true){ check[i].checked=false; } } } function fun3(){ var check = document.getElementsByName(‘check‘); for(var i=0;i<check.length;i++){ if(check[i].checked==true){ check[i].checked=false; }else{ check[i].checked=true; } } } function fun4(){ var arr = document.getElementsByName(‘check‘); var ar = []; for(var i=0;i<arr.length;i++){ if(arr[i].checked==true){ ar.push(arr[i].value); } } var id = ar.toLocaleString(); if(id==‘‘){ alert(‘請先選擇一項‘); return false; }else{ //ajax請求 var ajax = new XMLHttpRequest(); ajax.open("get","delete.php?id="+id); ajax.send(); ajax.onreadystatechange=function(){ if(ajax.readyState==4 && ajax.status==200){ //alert(ajax.responseText); //成功 if(ajax.responseText==1){ for(var i=0;i<ar.length;i++){ var tr=document.getElementById(ar[i]); tr.remove(); } } } } } } </script>

delete.php

<?php
//接收傳值
$id = $_GET[‘id‘];
//鏈接數據庫
$link = mysqli_connect(‘127.0.0.1‘,‘root‘,‘root‘,‘mone‘);
//設置字符集
mysqli_query($link,‘set names utf8‘);
//拼接sql
$sql = "DELETE FROM user WHERE user_id in ($id)";
if(mysqli_query($link,$sql)){
    echo 1;
}else{
    echo 2;
}

ajax全選、全不選、反選、單刪/批刪