1、贴个动图演示完成的效果
2、附上list.php源代码
其它代码和老师写的基本一样,以后写完整小项目时一并贴出
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>员工管理系统</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<table>
<caption>员工管理系统</caption>
<thead>
<tr>
<td>编号</td>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
<td>工资</td>
<td>邮箱</td>
<td>生日</td>
<td>入职时间</td>
<td>操作</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
<p></p>
</body>
<script>
const tbody = document.querySelector("tbody");
const p = document.querySelector("p");
const frag = new DocumentFragment();
const even = new Event('click');
p.addEventListener("click", ev => {
ev.preventDefault();
let page_num;
//利用事件代理的特性判断是否为页面第一次加载,并执行对应操作
if(ev.currentTarget.innerText === ev.target.innerText){
if (ev.target.innerHTML){
page_num = false;
}else{
page_num = 1;
}
}else{
//利用split()方法将url字符串切分为一个数组,取后面的页数
page_num = (ev.target.href).split('p=');
page_num = parseInt(page_num[1]);
}
if (page_num){
// 1、创建xhr对象
const xhr = new XMLHttpRequest();
// 2、配置参数
xhr.open('get','api.php?p=' + page_num);
xhr.responseType = "json";
// 3、处理响应
xhr.onload=()=>{
let staffs = xhr.response.staffs;
let pages = parseInt(xhr.response.pages);
let htmlstr = '';
for(let i = 0; i <staffs.length; i++){
htmlstr = htmlstr + `<tr><td>${staffs[i].sid}</td><td>${staffs[i].name}</td><td>${staffs[i].age}</td><td>${staffs[i].gender}</td><td>${staffs[i].salary}</td><td>${staffs[i].email}</td><td>${staffs[i].birthday}</td><td>${staffs[i].create_at}</td><td><button onclick="location.href='handle.php?action=edit&sid=${staffs[i].sid}'">编辑</button><button onclick="del(${staffs[i].sid})">删除</button></td></tr>`;
};
if (page_num !== 1){
const create_a = document.createElement("a");
create_a.innerText = '首页';
create_a.href = `/list.php?p=1`;
frag.appendChild(create_a);
}
if (page_num !== 1){
const create_a = document.createElement("a");
create_a.innerText = '上一页';
create_a.href = `/list.php?p=${page_num - 1}`;
frag.appendChild(create_a);
}
for(let i = 1; i <= pages; i++){
const create_a = document.createElement("a");
create_a.innerText = i;
create_a.href = `/list.php?p=${i}`;
if (page_num == i){
create_a.classList.add("active")
};
frag.appendChild(create_a);
};
if (page_num !== pages){
const create_a = document.createElement("a");
create_a.innerText = '下一页';
create_a.href = `/list.php?p=${page_num + 1}`;
frag.appendChild(create_a);
}
if (page_num !== pages){
const create_a = document.createElement("a");
create_a.innerText = '尾页';
create_a.href = `/list.php?p=${pages}`;
frag.appendChild(create_a);
}
tbody.innerHTML = htmlstr;
p.innerHTML = '';
p.appendChild(frag);
};
// 4、发送xhr内容
xhr.send(null);
}
});
// 事件派发,触发第一次异步加载内容
p.dispatchEvent(even);
// 删除信息时,弹出消息提示框
function del(sid) {
let url = 'handle.php?action=del&sid='+sid;
return confirm('是否删除编号为: '+sid+' 的员工信息?') ? location.href = url : false;
}
</script>
</html>