基于layui的表格异步删除,ajax的简单运用
h话不多说,看图,点击删除,出现确认框,然后点击确认删除,直接删除数据,
因为是基于面向过程的,没有用php框架写,所以有3个文件:
第一个文件:data.php:用于从数据库中获取数据
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
}
catch(PDOException $e){
echo "数据库连接失败:".$e->getMessage();
exit;
}
$query = "select * from info";
$pdostatement = $pdo->query($query);
$result = $pdostatement->fetchAll(PDO::FETCH_ASSOC);
第二个文件:index.php 展示页面;
<?php
include "./data.php";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<link rel="stylesheet" href="./css/layui.css" media="all">
</head>
<body>
<table class="layui-table">
<colgroup>
<col width="150">
<col width="200">
<col>
</colgroup>
<thead>
<tr>
<th>ID</th>
<th>名称></th>
<th>级别</th>
<th>编号</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<?php foreach($result as $key=>$v):?>
<tr>
<td><?php echo $v['id']?></td>
<td><?php echo $v['name']?></td>
<td><?php echo $v['level']?></td>
<td><?php echo $v['code_name']?></td>
<td><button class="delete">删除</button></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
</body>
</html>
<script src="./layui/layui.js"></script>
<script src="./js/jquery-1.10.2.min.js"></script>
<script>
$(function(){
layui.use('layer', function(){
var layer = layui.layer;
$(".delete").click(function(){
var id =$(this).parents('tr').find('td').eq(0).html();
layer.confirm("确认删除?",function(){
layer.msg(id);
$.ajax({
url: "./do_delete.php" ,
data: {'id':id} ,
type: "post" ,
dataType:'json',
success:function(data){
if(data.code==200){
location.reload();
}else{
layer.msg("删除失败");
}
}
})
})
})
});
})
</script>
第三个页面:do_delete.php :ajax的处理页面:
<?php
try{
$pdo = new PDO("mysql:host=localhost;dbname=test","root","root");
}
catch(PDOException $e){
echo "数据库连接失败:".$e->getMessage();
exit;
}
$id = $_POST["id"];
$query = "delete from info where id='$id'";
$result = $pdo->exec($query);
if($result){
echo json_encode(array("code"=>200));
}else{
echo json_encode(array('code'=>400));
}
上面就是全部代码,基于mvc的也是一样的思路,比这个更简单,可以自己试试看,