Blogger Information
Blog 61
fans 1
comment 0
visits 69763
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
0621-用户管理系统
我的博客
Original
920 people have browsed it

实例  用户管理系统 staff类库

<?php

namespace inc;

use PDO;

class Staff
{       //1、连接数据库
    private $pdo = null;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
    // 列出用户
    // $num: 每页记录数量, $page: 当前页码
    public function list($num, $page)
    {
        $offset = $num * ($page - 1);
        $sql = "SELECT * FROM `staff` LIMIT {$num} OFFSET {$offset}";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();

        // 调试: 查看生成的SQL语句
       // echo $stmt->debugDumpParams();

        // 将查询结果集以二维数组的方式返回
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }

    // 新增用户
    public function insert()
    {
        // 对于前端发送来的JSON字符串, PHP无法直接接收解析,需要使用原始流进行接收
        // file_get_contents(),将接收到的文件或内容(字符串形式)保存到变量中
//        echo file_get_contents('php://input');
//        die;

        $jsonStr = file_get_contents('php://input');
        // json_decode(),第二个参数默认为false,返回对象, true,返回数组
//        $staff = json_decode($jsonStr, false);
        $staff = json_decode($jsonStr, true);

        if (empty($staff['name']) || empty($staff['age']) || empty($staff['position']) || empty($staff['mobile'])) {
            echo json_encode(['status' => 2, 'message'=>'员工基本信息不能为空']);
            exit;
        }

        // 入职时间默认为当前的时间戳
        $staff['hiredate'] = time();

//        var_dump($staff); // 数组
//        die;

        // extract(): 将关联数组转变量, compace(),将多个变量转关联数组
        extract($staff);
//        echo $name, $age, $sex, $position, $mobile, $hiredate;
//        die;
        // 拼装SQL语句, 考虑到INSERT 语句比较长,采用了多行字符串的语法, NOWDOC语法
        $sql = <<< 'INSERT_SQL'
             INSERT INTO `staff`
              (`staff_id`,`name`,`age`,`sex`,`position`,`mobile`,`hiredate`)
              VALUES (NULL,:name,:age,:sex,:position,:mobile, :hiredate);
INSERT_SQL;
//        echo $sql; die;

        // 执行SQL操作
        $stmt = $this->pdo->prepare($sql);

        // 将变量绑定到SQL语句模板对象: PDOStement
        $stmt->bindParam('name', $name, PDO::PARAM_STR);
        $stmt->bindParam('age', $age, PDO::PARAM_INT);
        $stmt->bindParam('sex', $sex, PDO::PARAM_INT);
        $stmt->bindParam('position', $position, PDO::PARAM_STR);
        $stmt->bindParam('mobile', $mobile, PDO::PARAM_STR);
        $stmt->bindParam('hiredate', $hiredate, PDO::PARAM_INT);
        $stmt->execute();
        // 如果直接将$staff数组做为参数传递给execute()方法, 默认都是字符类型,无法指定具体类型
        // 如果涉及查询条件,会出问题,例如,显示数量等
//        $stmt->execute($staff);
//        echo $stmt->debugDumpParams();die;

        if ($stmt->rowCount() === 1) {
            $result = ['status'=>1, 'message'=>'添加成功'];
        } else {
            $result = ['status'=>0, 'message'=>'添加失败'];
        }
        // 将执行结果再经JSON格式返回到前端
        echo json_encode($result);
        exit();
    }

    // 编辑
    public function update($staffId)
    {

        $sql = 'SELECT * FROM `staff` WHERE `staff_id` = :staff_id';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['staff_id'=>$staffId]);

        $staff = [];
        if ($stmt->rowCount() === 1) {
            $staff = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        echo json_encode($staff);
        die;
    }

    // 执行编辑操作
    public function doEdit()
    {
        $jsonStr = file_get_contents('php://input'); //php不能直接识别JSON,用这个方法接原始数据流转换成JSON 格式
        // 将前端接收到的JSON转为PHP数组格式
        $staff = json_decode($jsonStr, true);    // 将前端接收到的JSON转为PHP数组格式

        // 准备更新语句的模板  //<<< 'UPDATE_SQL定界符
        $sql = <<< 'UPDATE_SQL'
            UPDATE `staff` 
            SET `name`=:name, `age`=:age, `sex`=:sex, `position`=:position,`mobile`=:mobile
            WHERE `staff_id` = :staff_id;
UPDATE_SQL;

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($staff);

        switch ($stmt->rowCount())
        {
            case 0:
                $result = ['status'=>0, 'message'=>'没有数据被更新'];
                break;
            case 1:
                $result = ['status'=>1, 'message'=>'更新成功'];
                break;
            default:
                $result = ['status'=>2, 'message'=>'未知错误或更新失败'];
        }

        // 将执行结果再经JSON格式返回到前端
        echo json_encode($result);
        exit();
    }

    public function find($name){
       $name = isset($name)? $name : null ;
        //$offset = $num * ($page - 1);
        //SELECT * FROM `staff` WHERE `name` LIKE '小' LIMIT 50
//        $sql = "SELECT '. * . ' FROM '.`staff`. ' WHERE '. `name` . ' LIKE ' . $name .' LIMIT ' . 50";
//        $sql = "SELECT * FROM `staff` LIMIT {$num} OFFSET {$offset}";

        $sql = "SELECT * FROM `staff` WHERE `name` LIKE '%{$name}%' LIMIT 5 OFFSET 0";


        // 调试: 查看生成的SQL语句

        // 将查询结果集以二维数组的方式返回
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        $finds=$stmt->fetchAll(PDO::FETCH_ASSOC);
       // $stmt->debugDumpParams();
        return $finds ;

    }



    // 删除操作
    public function delete($id)
    {
        $sql = 'DELETE FROM `staff` WHERE `staff_id` = :staff_id';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['staff_id'=>$id]);
        if ($stmt->rowCount() === 1) {
            $result = ['status'=>1, 'message'=>'删除成功'];
        } else {
            $result = ['status'=>0, 'message'=>'删除失败'];
        }
        // 将执行结果再经JSON格式返回到前端
        echo json_encode($result);
        exit();

    }

    // 编辑
    public function update1($staffId)
    {

        $sql = 'SELECT * FROM `staff` WHERE `staff_id` = :staff_id';
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(['staff_id'=>$staffId]);

        $staff = [];
        if ($stmt->rowCount() === 1) {
            $staff = $stmt->fetch(PDO::FETCH_ASSOC);
        }

        echo json_encode($staff);
        die;
    }

    // 修改密码
    public function np($password)
    {   //file_get_contents将真个文件读入到一个字符串
        $jsonStr = file_get_contents('php://input'); //php不能直接识别JSON,用这个方法接原始数据流转换成JSON 格式
        // 将前端接收到的JSON转为PHP数组格式
        $staff = json_decode($jsonStr, true);    // 将前端接收到的JSON转为PHP数组格式

        // 准备更新语句的模板  //<<< 'UPDATE_SQL定界符
        $sql = "SELECT * FROM `user` WHERE `email`='admin@php.cn'";
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute($staff);
        $stmt->debugDumpParams();
        $res= $stmt->fetchAll(PDO::FETCH_ASSOC);
       // echo print_r($res[0]['user_id'],true);

        $sql = "UPDATE  `user` SET `password`=sha1('{$password}') WHERE `user_id` = '{$res[0]['user_id']}'"; //变量加大括号,在加''号表示字符串
        $stmt = $this->pdo->prepare($sql);
        $stmt->execute();
        $stmt->debugDumpParams();

        $result= $stmt->fetchAll(PDO::FETCH_ASSOC);


        switch ($stmt->rowCount())
        {
            case 0:
                $result = ['status'=>0, 'message'=>'密码没有更新成功'];
                break;
            case 1:
                $result = ['status'=>1, 'message'=>'密码更新成功'];
                break;
            default:
                $result = ['status'=>2, 'message'=>'未知错误或更新失败'];
        }

        // 将执行结果再经JSON格式返回到前端
        echo json_encode($res[0]['user_id']);
        exit();
    }





    // 退出登录
    public function logout()
    {
        session_destroy();
        echo json_encode(['status'=>1, 'message'=>'退出成功']);
        exit;
    }

}

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例   staff_manage.php 实现按用户名查找,修改管理员密码,还有待继续改动

<?php
//开启会话
session_start();
//require 'caozuo.php';

// $_SERVER['QUERY_STRING']: 获取URL中的查询字符串(键值对)
// http://php.io/0620/staff_manage.php?action=list?p=1
//echo $_SERVER['REQUEST_URI'],'<br>';
// strstr($str, $searchStr, true): 返回$searchStr之前的字符,获取除页码之前的URL地址
// 使用p=当作标志位进行切割
//http://php.io/0620/staff_manage.php?action=list?
//echo strstr($_SERVER['REQUEST_URI'], 'p=', true), '<br>';
//echo $_SERVER['QUERY_STRING'],'<br>';
// 将查询字符串解析到数组中
//parse_str($_SERVER['QUERY_STRING'], $params);
//print_r($params);// Array ( [action] => list [p] => 2 )



// 连接数据库
require 'inc/connect.php';

// 加载Staff类并实例化
require 'inc/Staff.php';

$staff = new inc\Staff($pdo);

// 当前页数
// print_r($_GET);

// 当前的页码, 默认为1
$page = ($_GET['p']) ??  1;
// 获取当前请求类型

$action = $_GET['action'];
echo $action;
// 每页显示的记录数量
$num = 6;

// 总页数= 总数据条数/每页的条数 ,然后向上取整  //这一部分是计算显示list的总页数
$sql = "SELECT CEIL(COUNT(*)/{$num}) FROM `staff`";
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->fetchColumn(0);  //绑定0列,所有用户的索引值,从0开始
//echo $total;die;





// 判断应该执行的操作
switch ($action)
{
    // 员工列表
    case 'list':

        $staffs = $staff->list($num, $page);
        break;

    // 新增员工
    case 'insert':
        $staff->insert();
        break;

    // 更新
    case 'update':
        $staff->update1($_GET['id']);
        break;

    // 更新操作
    case 'doEdit':
        $staff->doEdit();
        break;
   // 查找操作
    case 'find':                                     //这里是find操作

        $staffs = $staff->find( $_GET['name']);


    break;

    // 删除操作
    case 'delete':
        $staff->delete($_GET['id']);
        break;
        //修改密码
    case 'ps3':
        echo $_GET['ps3'];
        $staff->np($_GET['ps3']);
        break;

    // 退出登录操作
    case 'logout':
        $staff->logout();
        break;
}

?>





<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="static/css/bootstrap.css">
    <title>后台首页</title>
</head>
<body>

<!--  **************  公共部分,不论什么时候都显示调用****************-->

<div class="container">
    <div class="row">
        <!--        判断用户是否登录?-->
        <div class="col-md-10 col-md-offset-1">
            <?php if (isset($_SESSION['user_id'])) :?>

                <!--        顶部导航-->
                <nav class="navbar navbar-default" style="border-radius: 0;background-color: lightblue">
                    <div class="container-fluid">
                        <div class="navbar-header">
                            <a class="navbar-brand" href="#">用户管理系统</a>
                        </div>
                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <li><a href="#"><?php echo $_SESSION['username'];?></a></li>
                                <li class="dropdown">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">操作 <span class="caret"></span></a>
                                    <ul class="dropdown-menu">
                                        <li><a href="#" type="button" data-toggle="modal" data-target="#myModal">修改密码</a></li>
                                        <li><a href="#" onclick="logout();return false;">退出</a></li>
                                    </ul>
                                </li>
                            </ul>
                        </div>
                    </div>
                </nav>

                <!--            显示用户信息与基本操作-->
                <table class="table table-bordered table-hover">
                    <caption><h3 class="text-center">用户信息表</h3></caption>
                    <thead>
                    <tr class="bg-info text-center">
                        <td>ID</td>
                        <td>姓名</td>
                        <td>年龄</td>
                        <td>性别</td>
                        <td>职位</td>
                        <td>手机</td>
                        <td>入职时间</td>
                        <?php if($_SESSION['username'] === 'admin') : ?>
                            <td>操作</td>
                        <?php endif; ?>
                    </tr>
                    </thead>

                    <tbody>
                    <?php foreach ($staffs as $staff ): ?>
                    <tr class="text-center">
                        <td><?php echo $staff['staff_id']?></td>
                        <td><?php echo $staff['name']?></td>
                        <td><?php echo $staff['age']?></td>
                        <td><?php echo $staff['sex'] ? '男' : '女' ?></td>
                        <td><?php echo $staff['position']?></td>
                        <td><?php echo $staff['mobile']?></td>
                        <td><?php echo date('Y-m-d',$staff['hiredate']) ?></td>
                        <?php if ($_SESSION['username'] === 'admin'): ?>
                        <td>
                            <button type="button" class="btn btn-info btn-sm" data-toggle="modal" data-target="#update" onclick="edit(document.forms.namedItem('update'),<?php echo $staff['staff_id']?>)">编辑</button>
                            <button class="btn btn-danger btn-sm"  onclick="isDel(this,<?php echo $staff['staff_id'];?>)">删除</button>
                        </td>
                        <?php endif; ?>
                    </tr>
                    <?php endforeach;?>
                    </tbody>
                </table>





<!--                搜索功能               -->
                <div class="pull-left">
                   <form action="" class="form-group form-inline">
                       <label for="search"></label>
                       <input type="text" class="form-control" placeholder="输入姓名" id="search">
                      <button class="btn btn-info btn-sm" id = 'fbtn' type="button">搜索</button>
                   </form>


               </div>
<!--                添加功能, 使用模态框来做-->
                <div class="pull-right"><button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#insert">添加</button></div>


<!--                分页条-->
                <nav class="text-center">
                    <ul class="pagination">
                        <?php
                        $url = strstr($_SERVER['REQUEST_URI'], 'p=', true);

                        // 前一页, 重点是越界处理,当前页为0时, 始终保证为1即可
                        $prev = $_GET['p']-1;
                        $prev = ($prev <= 0) ? 1 : $prev;
                        echo '<li><a href='.$url.'p='.$prev .'>前一页</a></li>';

                        for ($i = 1; $i <= $total; $i++){
                            // 设置当前页亮亮, 页码与当前的get参数p相等
                            $active = ($i == $_GET['p']) ? 'active' : '';
                            echo "<li class='{$active}'><a href='{$url}p={$i}'>{$i}</a></li>";
                        }

                        // 下一页: 与前一页功能类似, 重点也是对于页码越界的处理
                        $next = $_GET['p']+1;
                        // 如果当前页大于最大页码则只输出当前页,不再递增
                        $next = ($next >= $total) ? $total : $next;
                        echo '<li><a href='.$url.'p='.$next .'>下一页</a></li>';

                        ?>
                    </ul>
                </nav>



            <?php else :?>
                <script>alert('请登录');location.href='login.php';</script>
            <?php endif;?>
        </div>
    </div>

<!--添加数据的模态框-->
    <div class="modal fade" id="insert" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                    <h4 class="modal-title text-center" id="myModalLabel">添加员工</h4>
                </div>
                <div class="modal-body">
                    <form name="insert">
                        <div class="form-group">
                            <label for="name">姓名:</label>
                            <input type="text" class="form-control" id="name" placeholder="Name" required>
                        </div>
                        <div class="form-group">
                            <label for="age">年龄</label>
                            <input type="number" class="form-control" id="age" min="25" placeholder="Age" required>
                        </div>
                        <div class="form-group">
<!--                            label中的for也input中的id绑定, 单击会直接选择对应的按钮-->
                            <label for="1">性别:</label>
<!--                            后面的label,推荐将for与radio中的value属性值设置成一样的,并且value与id也一样-->
                            <input type="radio" id="1" name="sex" value="1" checked><label for="1">男</label>
                            <input type="radio" id="0" name="sex" value="0"><label for="0">女</label>
                        </div>

                        <div class="form-group">
                            <label for="position">职务:</label>
                            <input type="text" class="form-control" id="position" placeholder="Position" required>
                        </div>

                        <div class="form-group">
                            <label for="mobile">手机:</label>
                            <input type="text" class="form-control" id="mobile" placeholder="Mobile" required>
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<!--                    以当前表单做为参数,调用save()函数完成数据的添加操作-->
                    <button type="button" class="btn btn-primary"  onclick="save(document.forms.namedItem('insert'))">保存</button>
<!--                    信息提示框-->
                    <div class="alert alert-success  pull-left" role="alert" id="alert1" style="display: none">
<!--                        登录成功-->
                    </div>
                </div>
            </div>
        </div>
    </div>


</div>

<!--编辑用户的模态框-->
<div class="modal fade" id="update" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title text-center" id="myModalLabel">编辑员工信息</h4>
            </div>
            <div class="modal-body">
                <form name="update">
                    <div class="form-group">
                        <label for="name">姓名:</label>
                        <input type="text" class="form-control" id="name">
                    </div>
                    <div class="form-group">
                        <label for="age">年龄</label>
                        <input type="number" class="form-control" id="age" min="25">
                    </div>
                    <div class="form-group">
                        <!--                            label中的for也input中的id绑定, 单击会直接选择对应的按钮-->
                        <label for="1">性别:</label>
                        <!--                            后面的label,推荐将for与radio中的value属性值设置成一样的,并且value与id也一样-->
                        <input type="radio" id="1" name="sex" value="1" checked><label for="1">男</label>
                        <input type="radio" id="0" name="sex" value="0"><label for="0">女</label>
                    </div>

                    <div class="form-group">
                        <label for="position">职务:</label>
                        <input type="text" class="form-control" id="position">
                    </div>

                    <div class="form-group">
                        <label for="mobile">手机:</label>
                        <input type="text" class="form-control" id="mobile">
                    </div>

                    <!--                    需要额外增加一个隐藏域,保存正在编辑的员工主键id,这是前后端数据交互的依据,这个数据不需要展现给用户-->
                    <input type="hidden" name="staff_id">

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <!--                    以当前表单做为参数,调用save()函数完成数据的添加操作-->
                <!--                doEdit()是真正执行更新的操作, 只需要将当前表单做为参数即可, 可以通过该表单获取到所有需要更新的数据-->
                <button type="button" class="btn btn-primary"  onclick="doEdit(document.forms.namedItem('update'))">保存</button>
                <!--                    信息提示框-->
                <div class="alert alert-success  pull-left" role="alert" id="alert2" style="display: none">
                    <!--                        保存成功-->
                </div>
            </div>
        </div>
    </div>
</div>


<!--删除操作的模态框-->
<div class="modal fade" id="delete" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<!--                <h4 class="modal-title text-center" id="myModalLabel">删除用户</h4>-->
            </div>
            <div class="modal-body">
                <h3 class="h3 text-center">是否真的删除?</h3>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <!--                    以当前表单做为参数,调用save()函数完成数据的添加操作-->
                <!--                doEdit()是真正执行更新的操作, 只需要将当前表单做为参数即可, 可以通过该表单获取到所有需要更新的数据-->
                <button type="button" class="btn btn-primary" id="del">删除</button>
                <!--                    信息提示框-->
                <div class="alert alert-success  pull-left" role="alert" id="alert2" style="display: none">
                    <!--                        保存成功-->
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Button 修改管理员密码模态框 -->
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <form class="form-horizontal">

                    <div class="form-group">
                        <label for="ip3" class="col-sm-2 control-label" >密码</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" id="ps3" placeholder="请输入要修改的密码">
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="ip3">保存</button>
            </div>
        </div>
    </div>
</div>

<script src="static/js/jquery-3.4.1.js"></script>
<script src="static/js/bootstrap.js"></script>

<script>
    //修改管理员密码代码


    var ps3 =document.getElementById('ps3');  //密码框
    var ip3 = document.getElementById('ip3');  //密码保存框按钮
    ip3.onclick=function () {
        console.log(ps3.value);
        var res = new XMLHttpRequest();
        res.onreadystatechange=function () {
            if(res.readyState===4){
                //console.log(res.responseText);
               // var obj = (this.responseText);
                 //console.log(obj);
            }

        };

        //post 发送还不熟练,先用GET发送
        // res.open('post','staff_manage.php?action=ps3',true);
        // res.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        // // 将表单数据打包到一个js对象中
        // var obj = {
        //     ps3 : ps3.value,
        //
        // };
        // // 将js对象转为json发送
        // var data = JSON.stringify(obj);
        // res.send(data);
        res.open('POST', 'staff_manage.php?action=ps3&p=1&ps3='+ps3.value, true);
        res.send(null);

    };








    //查找数据的代码
    var fbtn = document.getElementById('fbtn');
    var sc = document.getElementById('search');

    fbtn.onclick=function find() {


            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (request.readyState === 4) {
                    //console.log(request.responseText);
                    var text = request.responseText;
                    if(text){
                        location.assign('staff_manage.php?action=find&p=1&name='+sc.value);
                    }else if(text ===null ){
                        alert('什么都没有查到');
                    }else {
                        alert('查询错误');
                    }

                    }
            };
            request.open('GET', 'staff_manage.php?name='+sc.value, true);
            request.send(null);

    };




    // 添加数据函数: save()
    // ***************************insert事件*****************************
    function save(form) {

        // 表单数据的非空验证在服务器端由PHP完成

        // 非空验证完成后, 获取用户的基本信息
        var staffName = form.name.value;
        var staffAge = form.age.value;
        var staffSex = form.sex.value;
        var staffPosition = form.position.value;
        var staffMobile = form.mobile.value;

        //获取信息提示框
        var tips1 = document.getElementById('alert1');


        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                // console.log(this.responseText);
                var obj = JSON.parse(this.responseText);
                // console.log(obj);

                // 将提示框显示出来
                tips1.style.display = 'block';
                switch (obj.status) {
                    case 0:
                        // 设置警告信息提示框的样式: 黄色背景
                        tips1.classList.remove('alert-success');
                        tips1.classList.add('alert-warning');

                        tips1.innerText = obj.message;


                        // 模块点击事件, 2秒后自动点击关闭按钮
                        // javascript事件模拟:http://www.php.cn/js-tutorial-423451.html
                        setTimeout(function () {
                            // 选择要被自动点击的元素,如关闭按钮
                            var closeBtn = document.getElementsByClassName('close').item(0);
                            // 创建一个鼠标标准事件对象
                            var event = document.createEvent('MouseEvents');
                            // 初始化该事件对象,设置事件类型为单击, 可冒泡, 可取消
                            event.initMouseEvent('click',true, true);
                            // 将自定义鼠标单击事件分配给该按钮
                            closeBtn.dispatchEvent(event);
                        }, 2000);

                        break;
                    case 1:
                //         设置成功信息提示框的样式: 绿色背景
                        tips1.classList.remove('alert-warning');
                        tips1.classList.add('alert-success');

                        tips1.innerText = obj.message;

                        // 推荐使用一个函数来封装这个事件模拟程序,这里就直接复制了
                        // 模块点击事件, 2秒后自动点击关闭按钮
                        setTimeout(function () {
                            // 选择要被自动点击的元素,如关闭按钮
                            var closeBtn = document.getElementsByClassName('close').item(0);
                            // 创建一个鼠标标准事件对象
                            var event = document.createEvent('MouseEvents');
                            // 初始化该事件对象,设置事件类型为单击, 可冒泡, 可取消
                            event.initMouseEvent('click',true, true);
                            // 将自定义鼠标单击事件分配给该按钮
                            closeBtn.dispatchEvent(event);
                        }, 2000);

                        // 添加成功后, 自动刷新页面,显示出新增的记录
                        window.location.reload();

                        break;

                    case 2:
                        // 返回非空验证的提示信息
                        // 设置警告信息提示框的样式: 黄色背景
                        tips1.classList.remove('alert-success');
                        tips1.classList.add('alert-warning');

                        tips1.innerText = obj.message;
                        break;

                        // 如果返回了非上面的值,则提示用户
                    default:
                        tips1.innerHTML = '<span style="color:red">类型错误</span>';
                }
            }
        };
        request.open('POST', 'staff_manage.php?action=insert', true);
        // 将表单数据打包到一个js对象中
        var obj = {
            name: staffName,
            age: staffAge,
            sex: staffSex,
            position: staffPosition,
            mobile: staffMobile
        };
        // 将js对象转为json发送
        var data = JSON.stringify(obj);
        // console.log(data);
        // 设置请求头, 注意, 发送的JSON数据
        request.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        request.send(data); // 注意,现在发送到服务器端的是JSON字符串
    }





    // *****************update更新事件,先查找用户需要更新的对象****************************************
    // 编辑员工信息的点击事件函数
    // 编辑操作,需要一表用来编辑数据表单, 以及需要编辑的记录
    // 所以,需要传入二个参数, 一个是编辑表单, 二是根据主键获取的要编辑的记录
    function edit(form, id) {
        var request = new XMLHttpRequest();
        request.onreadystatechange = function () {
            if (this.readyState === 4) {
                // console.log(this.responseText);
                // 获取编辑模态框中的编辑表单
                // console.log(form);
                // 将服务器返回的要编辑的记录,JSON转为JS对象
                var obj = JSON.parse(this.responseText);

                // 将对应的数据,填充到指定的表单控件元素中
                form.name.value = obj.name;
                form.age.value = obj.age;
                form.sex.value = obj.sex;
                form.position.value = obj.position;
                form.mobile.value = obj.mobile;
                // 隐藏域的值
                form.staff_id.value = obj.staff_id;
            }
        };

        // GET请求, 更新操作, 需要将需要更新的员工主键ID做为参数传递到服务器端
        request.open('GET', 'staff_manage.php?action=update&id='+id, true);
        request.send(null);
    }



    //*********************doEdit将添加到数据库的新数据更新到页面******************************
    // 保存已更新的员工信息操作
    function doEdit(form) {
        var requset = new XMLHttpRequest();
        requset.onreadystatechange = function () {
            if (this.readyState === 4) {
                console.log(this.responseText);

                // 获取信息提示框
                var tips2 = document.getElementById('alert2');
                // 将提示框显示出来
                tips2.style.display = 'block';

                var jsObj = JSON.parse(this.responseText);

                switch (jsObj.status) {
                    case 0:
                        tips2.innerHTML = '<span style="color:red">'+jsObj.message+'</span>';
                        break;
                    case 1:
                        tips2.innerHTML = jsObj.message;
                        break;
                    case 2:
                        tips2.innerHTML = '<span style="color:red">'+jsObj.message+'</span>';
                        break;
                }

                // 模块点击事件, 2秒后自动点击关闭按钮
                setTimeout(function () {
                    var closeBtn = document.getElementsByClassName('close').item(1);
                    // 创建一个鼠标标准事件对象
                    var event = document.createEvent('MouseEvents');
                    // 初始化该事件对象,设置事件类型为单击, 可冒泡, 可取消
                    event.initMouseEvent('click',true, true);
                    // 将自定义鼠标单击事件分配给该按钮
                    closeBtn.dispatchEvent(event);
                }, 2000);

                // 更新成功后, 自动刷新页面,显示最新数据
                window.location.reload();

            }
        };

        // 准备需要更新的数据
        var $obj = {
            staff_id: form.staff_id.value,
            name: form.name.value,
            age: form.age.value,
            sex: form.sex.value,
            position: form.position.value,
            mobile: form.mobile.value
        };

        // 将JS对象转JSON字符串
        var data = JSON.stringify($obj);

        requset.open('POST', 'staff_manage.php?action=doEdit', true);
        requset.send(data);
    }



    // 是否删除与执行删除操作
    function isDel(ele,id) {
        ele.setAttribute('data-toggle','modal');
        ele.setAttribute('data-target','#delete');

        // 给模态框的删除按钮添加点击事件
        var delBtn = document.getElementById('del');

        delBtn.onclick = function () {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (this.readyState === 4) {
                    // console.log(this.responseText);
                    var obj = JSON.parse(this.responseText);
                    if (obj.status === 1) {
                        // 为简化,这里直接用弹窗输出, 大家可以改为Bootstrap信息提示框
                        alert(obj.message);
                    }
                    else {
                        alert(obj.message);
                    }

                    // 模块点击事件, 2秒后自动点击关闭按钮
                    setTimeout(function () {
                        var closeBtn = document.getElementsByClassName('close').item(2);
                        // 创建一个鼠标标准事件对象
                        var event = document.createEvent('MouseEvents');
                        // 初始化该事件对象,设置事件类型为单击, 可冒泡, 可取消
                        event.initMouseEvent('click',true, true);
                        // 将自定义鼠标单击事件分配给该按钮
                        closeBtn.dispatchEvent(event);
                    }, 2000);

                    // 删除成功后, 自动刷新页面
                    window.location.reload();

                }
            };
            request.open('GET', 'staff_manage.php?action=delete&id='+id, true);
            request.send(null);
        }
    }


    // 退出登录
    function logout() {
        if (confirm('是否真的退出?')) {
            var request = new XMLHttpRequest();
            request.onreadystatechange = function () {
                if (this.readyState === 4) {
                    console.log(this.responseText);
                    var obj = JSON.parse(this.responseText);
                    if (obj.status === 1) {
                        alert(obj.message);
                        location.href = 'login.php';
                    }
                }
            };
            request.open('GET', 'staff_manage.php?action=logout', true);
            request.send(null);
        }
    }



</script>
</body>
</html>


<!--该项目,还有二个功能未实现:-->
<!--1. 管理员的信息修改,如邮箱,密码-->
<!--2. 员工搜索功能,默认根据员工姓名搜索-->
<!--这是二个小作业 ,供大家周未完成-->

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post