博客列表 >0621作业2019年06月24日11:26:36

0621作业2019年06月24日11:26:36

Viggo的博客
Viggo的博客原创
2019年06月24日 11:36:021006浏览

给老师的代码添加搜索功能、修改密码功能、记住密码功能。

搜索功能通过get方式提交,在地址栏添加一个get参数 ss , 

staff_manage.php打开的时候获取这个参数 判断是否要搜索,把查询字段传入list进行查询。


修改密码功能,新建一个模态框,利用修改密码按钮触发这个模态框,然后用ajax方式发送数据给staff.php进行判断操作

这个功能和编辑功能和添加功能类似。


记住密码功能,利用cookie实现,cookie的数据应该加密,目前没有学习不会。

在打开login.php的时候 邮箱、密码、复选框、都利用php获取cookie进行设置填充数据。

login.php 异步提交的时候判断复选框是否选中然后把remember值传入给后端php页面。

在user.php中判断这个值然后做相应的处理。



login.php

实例

<?php
//session_start();
//echo $_COOKIE['email'];
?>

<!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">
        <h3 class="text-center">用户登录</h3>
        <div class="col-md-6 col-md-offset-3">
<!--            给form添加name属性,便于再加直观的获取表单-->
            <form class="form-horizontal"  name="login">
                <div class="form-group">
                    <label for="email" class="col-sm-2 control-label">邮箱:</label>
                    <div class="col-sm-10">
                        <input type="email" class="form-control" name="email" id="email" placeholder="Email" value="<?=$_COOKIE['email']?>">
                    </div>
                </div>
                <div class="form-group">
                    <label for="password" class="col-sm-2 control-label">密码:</label>
                    <div class="col-sm-10">
                        <input type="password" class="form-control" name="password" id="password" placeholder="Password" value="<?=$_COOKIE['password']?>">
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <div class="checkbox">
                            <label>
<!--                                <input type="checkbox" name="remember"> 是否记住-->
                                <?php
                                if (isset($_COOKIE['remember']))
                                {
                                    echo '<input type="checkbox" name="remember" checked> 是否记住';
                                }else{
                                    echo '<input type="checkbox" name="remember"> 是否记住';
                                } ?>

                            </label>
                        </div>
                    </div>
                </div>
                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="button" class="btn btn-primary btn-block">登录</button>
                    </div>
                </div>

<!--                登录信息的提示, 初始化时先隐藏-->
                <div class="alert  col-sm-offset-2 col-sm-10" role="alert" id="alert" style="display: none">

                </div>
            </form>
        </div>
    </div>
</div>

<script>
    // 获取登录表单
    var login = document.forms.namedItem('login');
    //获取信息提示框
    var tips = document.getElementById('alert');
    // 获取Ajax对象
    var request = new XMLHttpRequest();

    // 获取登录按钮
    var btn = document.querySelector('button');

    // 设置登录事件的方法
    btn.addEventListener('click', isEmpty,false);

    // 验证用户输入是否为空?
    function isEmpty() {
        if (login.email.value.trim().length === 0 || login.password.value.trim().length === 0) {
           alert('邮箱和密码不能为空');
        } else {
            check();
        }
    }

    if (login.remember.checked) { //如果选中了记住密码就写入session
        var remember = 'auto';
    }else { //否则就删除session
        var remember = '';
    }

    // 验证用户输入的信息是否正确?
    function check() {
        // 监听请求的回调
        request.addEventListener('readystatechange', callback, false);
        // 设置请求参数
        request.open('POST', 'user_manage.php?action=login', true);
        // 设置请求头,用户信息以表单数据格式进行发送
        request.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        // 发送请求
        request.send('email='+login.email.value+'&password='+login.password.value+'&remember='+remember);
    }

    // 对用户登录信息的异步验证
    function callback() {
        if (request.readyState === 4)  {
            // console.log(request.responseText);
            var obj = JSON.parse(request.responseText);

            // 将提示框显示出来
            tips.style.display = 'block';
            if (obj.status === 1) {
                // 设置成功信息提示框的样式: 绿色背景
                tips.classList.remove('alert-warning');
                tips.classList.add('alert-success');
                tips.innerText = obj.message;

                // 定时器, 2秒后进入后台管理首页
                setTimeout('location.href="staff_manage.php?action=list&p=1"', 1000);
            } else if (obj.status === 0) {
                // 设置警告信息提示框的样式: 黄色背景
                tips.classList.remove('alert-success');
                tips.classList.add('alert-warning');

                tips.innerText = obj.message;
            }
        }
    }

    // 验证失败,用户更新登录信息时,清除错误提示
    login.email.addEventListener('input', clearTips, false);
    login.password.addEventListener('input', clearTips, false);
    function clearTips(){
        tips.setAttribute('style', 'display: none');
    }

</script>


</body>
</html>

运行实例 »

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


user_manage.php

实例

<?php
// 开启会话, 使用SESSION
session_start();


$email = $_POST['email'];
$password = $_POST['password'];
$remember = $_POST['remember'];


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

// 加载User类
require 'inc/User.php';

// 实例化User类
$user = new inc\User($pdo);

// 根据GET参数判断用户要进行的操作是什么?
$action = $_GET['action'];

switch ($action)
{
    // 登录操作
    case 'login':
        $email = $_POST['email'];
//        $password = sha1($_POST['password']); //取消这里的加密转换 放在login()里面
        echo $user->login($email, $password, $remember);
        break;


}

运行实例 »

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

staff_manage.php

实例

<?php
//开启会话
session_start();

// $_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;
// 每页显示的记录数量
$num = 6;

// 总页数
//获取搜索get参数

$ss = $_GET['ss'];
//参数为空判断
$where = empty($ss) ? '' : " WHERE name like '%{$ss}%'";

$sql = "SELECT CEIL(COUNT(*)/{$num}) FROM `staff` {$where}"; //添加一个搜索条件
$stmt = $pdo->prepare($sql);
$stmt->execute();
$total = $stmt->fetchColumn(0);
//echo $total;die;

// 获取当前请求类型
$action = $_GET['action'];



// 判断应该执行的操作
switch ($action)
{
    // 员工列表
    case 'list':
        $staffs = $staff->list($num, $page, $where); //传入搜索条件
        break;

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

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

    // 更新操作
    case 'doEdit':
        $staff->doEdit();
        break;

    // 删除操作
    case 'delete':
        $staff->delete($_GET['id']);
        break;

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

//     修改密码
    case 'doModify':
        $staff->modify();
        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="#" data-toggle="modal" data-target="#modify">修改密码</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 name="search" class="form-group form-inline">
                       <label for="search"></label>
                       <input type="text" class="form-control" placeholder="输入姓名" id="search">
                      <button type="button" class="btn btn-info btn-sm" onclick="searchFor(document.forms.namedItem('search'))">搜索</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;
                        $ss = empty($ss) ? '' : '&ss='.$ss;
                        echo '<li><a href='.$url.'p='.$prev.$ss.'>前一页</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.$ss.'>下一页</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="alert3" style="display: none">
                    <!--                        保存成功-->
                </div>
            </div>
        </div>
    </div>
</div>

<!--修改密码的模态框-->
<div class="modal fade" id="modify" 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="modify" class="form-horizontal">

                    <div class="form-group">
                        <label for="username" class="col-sm-2 control-label">账号:</label>
                        <div class="col-sm-8">
                            <input type="text" class="form-control" id="username" value="<?php echo $_SESSION['username'];?>" disabled>
                            <p></p>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="name" class="col-sm-2 control-label">邮箱:</label>
                        <div class="col-sm-8">
                            <input type="email" class="form-control" id="email" value="<?php echo $_SESSION['email'];?>" disabled>
                            <p></p>
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="oldPassword" class="col-sm-2 control-label">原密码:</label>
                        <div class="col-sm-8">
                            <input type="password" class="form-control" id="oldPassword">
                        </div>
                    </div>

                    <div class="form-group">
                        <label for="newPassword" class="col-sm-2 control-label">新密码:</label>
                        <div class="col-sm-8">
                            <input type="password" class="form-control" id="newPassword">
                        </div>
                    </div>

                </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="doModify(document.forms.namedItem('modify'))">保存</button>
                <!--                    信息提示框-->
                <div class="alert alert-success  pull-left" role="alert" id="alert4" style="display: none">
                    <!--                        保存成功-->
                </div>
            </div>
        </div>
    </div>
</div>

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

<script>
    // 添加数据函数: save()
    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字符串
    }

    // 编辑员工信息的点击事件函数
    // 编辑操作,需要一表用来编辑数据表单, 以及需要编辑的记录
    // 所以,需要传入二个参数, 一个是编辑表单, 二是根据主键获取的要编辑的记录
    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);
    }


    // 保存已更新的员工信息操作
    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);
        }
    }

    // 搜索
    function searchFor(content) {
        var search = content.search.value;
        if (search === ''){
            content.search.focus(); //如果为空搜索输入框获取焦点,给用户反馈
        }else {
            location.replace('?action=list&p=1&ss='+content.search.value);
        }

    }

    // 修改密码
    function doModify(form) {
        // 非空验证 还可以再判断密码长度等要求
        if (form.oldPassword.value.trim().length === 0 || form.newPassword.value.trim().length === 0){
            alert('请输入需要修改的密码信息!');
            return false;
        }
        var xhm = new XMLHttpRequest();
        xhm.onreadystatechange = function () {
            if (this.readyState === 4) {
                console.log(this.responseText);

                // 获取信息提示框
                var tips2 = document.getElementById('alert4');
                // 将提示框显示出来
                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;
                }
            }
        };

        // 准备需要更新的数据
        var $obj1 = {
            name: form.username.value, //用户名
            oldPassword: form.oldPassword.value, //原密码
            newPassword: form.newPassword.value //新密码
        };

        // 将JS对象转JSON字符串
        var data1 = JSON.stringify($obj1);
        console.log(data1);

        xhm.open('POST', 'staff_manage.php?action=doModify', true);
        xhm.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
        xhm.send(data1);
    }

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

运行实例 »

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

实例

<?php

namespace inc;

use PDO;

class Staff
{
    private $pdo = null;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }
    // 列出用户
    // $num: 每页记录数量, $page: 当前页码
    public function list($num, $page, $where)
    {
        $offset = $num * ($page - 1);
        $sql = "SELECT * FROM `staff` {$where} 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');
        // 将前端接收到的JSON转为PHP数组格式
        $staff = json_decode($jsonStr, true);

        // 准备更新语句的模板
        $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 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 logout()
    {
        session_destroy();
        echo json_encode(['status'=>1, 'message'=>'退出成功']);
        exit;
    }

//    修改密码
    public function modify()
    {
//        PHP不能直接获取json格式,用这个方法获取
        $jsonStr = file_get_contents('php://input');
        // 将前端接收到的JSON转为PHP数组格式
        $staff = json_decode($jsonStr, true);


        $oldPassword = sha1($staff['oldPassword']);
        $newPassword = sha1($staff['newPassword']);
        $username = $staff['name'];


        // 准备更新语句的模板 查询账号和旧密码相同的一条数据进行更改
        $sql = <<< 'UPDATE_SQL'
            UPDATE `user` 
            SET `password`= :newpassword
            WHERE `username` = :username AND `password` = :oldpassword;
UPDATE_SQL;

        $stmt = $this->pdo->prepare($sql);
        $stmt->execute(array('newpassword'=>$newPassword,'username'=>$username,'oldpassword'=>$oldPassword));
//        $stmt->debugDumpParams();
//        die;

        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();
    }

}

运行实例 »

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

user.php

实例

<?php

namespace inc;
use \PDO;

class User
{
    private $pdo = null;

    public function __construct(PDO $pdo)
    {
        $this->pdo = $pdo;
    }

    // 登录操作
    public function login($email, $password, $remember)
    {
        $password_sha1 = sha1($password); //把密码加密成sha1

        $sql = 'SELECT * FROM `user` WHERE `email`= :email AND `password`= :password';

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

//        $stmt->execute(['email'=>$email, 'password'=>$password]);
        $stmt->execute(['email'=>$email, 'password'=>$password_sha1]);

        if ($stmt->rowCount() === 1) {
            // 验证成功,获取当前用户基本信息
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            // 将用户id和用户名和保存到SESSION中, 供后台调用
            $_SESSION['user_id'] = $user['user_id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['email'] = $user['email'];

            if (empty($remember))
            {
//                账号密码应该加密 暂时不会 如果改成session退出登录后session删除就无法记住密码登录了
                setcookie('remember','auto');
                setcookie('email',$user['email']);
                setcookie('password',$password);//客户填入的密码数据 不是sha1
            }else{
                setcookie('remember','',time()-1);
                setcookie('email','',time()-1);
                setcookie('password','',time()-1);
            }


            return json_encode(['status'=>1, 'message'=>'验证通过, 正在跳转中...']);
        } else {
            // 验证失败
            return json_encode(['status'=>0, 'message'=>'登录失败,请检查邮箱或密码']);
        }
    }
}

运行实例 »

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


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议