Ajax - 案例 - 英雄信息列表

index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>我们的68-英雄管理</title>
        <link rel="stylesheet" href="./libs/bootstrap/css/bootstrap.min.css" />
        <style>
            .panel {
                width: 900px;
                margin: 10px auto;
            }

            .table img {
                width: 40px;
                height: 40px;
            }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="panel panel-primary">
                <div class="panel-heading">英雄列表管理</div>
                <div class="panel-body">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="input-group">
                                <input type="text" id="hname" class="form-control" placeholder="输入英雄信息..." autocomplete="true" />
                                <span class="input-group-btn">
                                    <button class="btn btn-default" id="btn_search" type="button">搜索</button>
                                </span>
                            </div>
                        </div>

                        <div class="col-lg-3 col-lg-offset-3">
                            <button type="button" class="btn btn-success openDialog" data-toggle="modal" data-target="#addHeroModal">添加英雄</button>
                        </div>
                    </div>
                </div>

                <table class="table">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>英雄名称</th>
                            <th>英雄性别</th>
                            <th>头像</th>
                            <th>操作区</th>
                        </tr>
                    </thead>
                    <!-- 表格主体 -->
                    <tbody id="tbody"></tbody>
                </table>
            </div>
        </div>

        <!-- 添加英雄的模态框 -->
        <!-- 更改id,需要设置独立的id,避免重名;id要与触发按钮的id对应 -->
        <div class="modal fade" id="addHeroModal" 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">&times;</span>
                        </button>
                        <h4 class="modal-title" id="myModalLabel">添加英雄</h4>
                    </div>
                    <!--  -->
                    <div class="modal-body">
                        <form class="form-horizontal" id="addForm">
                            <div class="form-group">
                                <label for="heroName" class="col-sm-2 control-label">英雄名称</label>
                                <div class="col-sm-10">
                                    <input type="text" name="name" class="form-control" id="heroNameinput" placeholder="请输入英雄名称" />
                                </div>
                            </div>

                            <div class="form-group">
                                <label for="heroGender" class="col-sm-2 control-label">英雄性别</label>
                                <div class="col-sm-10">
                                    <select class="form-control" id="heroGenderselect" name="gender">
                                        <option></option>
                                        <option></option>
                                    </select>
                                </div>
                            </div>
                        </form>
                    </div>
                    <!-- 底部按钮 -->
                    <div class="modal-footer">
                        <input type="button" class="btn btn-success btnAdd" data-dismiss="modal" value="提交" />
                        <button type="button" class="btn btn-default btnCancel">取消</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 上传用户头像的模态框 -->
        <div class="modal fade" id="uploadModal" 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">&times;</span>
                        </button>
                        <h4 class="modal-title" id="myModalLabel">上传头像</h4>
                    </div>
                    <div class="modal-body">
                        <form id="formImg"></form>
                            <input type="file" name="" id="myimg" />
                        </form>
                    </div>
                    <div class="modal-footer">
                        <input type="button" class="btn btn-success btnUploadImg" data-dismiss="modal" value="提交" />
                        <button type="button" class="btn btn-default btnCancelUpload">取消</button>
                    </div>
                </div>
            </div>
        </div>

        <script src="./libs/jquery/jquery.min.js"></script>
        <script src="./libs/bootstrap/js/bootstrap.min.js"></script>
        <script src="./js/index.js"></script>
    </body>
</html>

index.js

$(function () {
    // 1.获取所有英雄列表数据,实现动态渲染

    // 函数封装ajax请求
    function init(userKey) {
        $.ajax({
            url: 'http://127.0.0.1:3001/getHeroList',
            type: 'get',
            data: { heroName: userKey },
            success: res => {
                console.log(res);
                if (res.code === 200) {
                    // 遍历数据,拼接生成动态结构
                    let html = '';
                    $.each(res.data, function (index, value) {
                        html += `
                            <tr>
                            <td>${index + 1}</td>
                            <td>${value.name}</td>
                            <td>${value.gender}</td>
                            <td>
                                <img src="${value.img}" alt="" />
                            </td>
                            <td>
                                <button type="button" class="btn btn-info btnUp" myId="${value.id}">上传头像</button>
                                <button type="button" class="btn btn-warning btnDel" id = "${value.id}">删除</button>
                            </td>
                        </tr>
                            `;
                    });

                    // 渲染到页面
                    $('#tbody').html(html);

                    // 聚焦
                    $('#hname').focus();

                    // 清空
                    $('#hname').val('');
                }
            },
        });
    }
    //调用函数,不传参,获取所有
    init();

    // 2.实现英雄数据的搜索
    $('#btn_search').on('click', () => {
        //   2.1 收集用户数据
        let userKey = $('#hname').val().trim();

        // 发起ajax请求,传取参数,获取数据,实现动态渲染
        init(userKey);
    });

    // 键盘事件调用点击事件
    $(document).on('keydown', e => {
        // console.log(e.keyCode);

        if (e.keyCode === 13) $('#btn_search').trigger('click');
    });

    // 3.实现英雄数据的新增
    $('.btnAdd').on('click', () => {
        //收集数据
        let name = $('#heroNameinput').val().trim();
        let gender = $('#heroGenderselect').val().trim();
        // console.log(name, gender);
        if (name === '') alert('请输入英雄名称');

        // 查看接口文档,发送ajax请求
        $.ajax({
            type: 'post',
            url: 'http://127.0.0.1:3001/addHero',
            data: { name, gender },
            success: res => {
                console.log(res);
                if (res.msg === '添加成功') {
                    alert(res.msg);

                    // 实现列表的刷新,就是调用之前的数据渲染的方法
                    init();

                    // 清空
                    $('#heroNameinput').val('');
                    $('#heroGenderselect').val('男');
                }
            },
        });
    });

    // 4.删除用户数据,事件委托
    // 动态生成的元素的事件绑定需要使用委托,因为在绑定事件的时候,元素还没有生成 ,因为异步非阻塞
    $('#tbody').on('click', '.btnDel', function () {
        // 询问用户是否真的删除,增加用户体验度
        if (confirm('请问是否真的需要删除')) {
            // 获取 id
            let id = $(this).prop('id');

            // ajax请求
            $.ajax({
                type: 'get',
                url: 'http://127.0.0.1:3001/delHeroById',
                data: { id: id },
                success: res => {
                    console.log(res);
                    alert(res.msg);
                    init();
                },
            });
        }
    });

    //  定义全局变量,保存id
    let heroId = undefined;
    // 5. 上传头像,事件委托
    $('#tbody').on('click', '.btnUp', function () {
        // 弹出模态框
        $('#uploadModal').modal('show');

        heroId = $(this).attr('myId');
    });

    // 6.实现文件上传的功能
    $('.btnUploadImg').on('click', () => {
        // 1.收集用户的头像数据
        // files:是原生方式的属性,只能使用dom进行调用
        let myfile = $('#myimg')[0].files[0];
        let formdata = new FormData();
        formdata.append('file_data', myfile);

        // 2.实现文件上传
        $.ajax({
            type: 'post',
            url: 'http://127.0.0.1:3001/uploadFile',
            data: formdata,
            contentType: false, //告诉ajax数据不是普通的字符串值,所以不用对其进行编码处理
            processData: false, // 告诉ajax不能对传递的参数进行任何的处理
            success: res => {
                console.log(res);

                // 文件上传成功后,更新用户数据
                // 根据后天接口的说明,更新用户头像,需要传入两个参数:id,img
                // id:当前用户的 id
                // img:就是刚刚上传文件,后台服务器返回图片的 url

                $.ajax({
                    type: 'post',
                    url: 'http://127.0.0.1:3001/updateHero',
                    // 💥💥💥 因为我们需要通过id来唯一的标识你想操作的数据
                    // 💥💥💥 总结: 凡是 编辑 或者 删除 ,都需要传入 id
                    data: { id: heroId, img: res.src },
                    success: res => {
                        console.log(res);
                        init();
                    },
                });
            },
        });
    });
});

index.html - 渲染页面改进,模板引擎

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>我们的67</title>
        <link rel="stylesheet" href="./libs/bootstrap/css/bootstrap.min.css" />
        <style>
            .panel {
                width: 900px;
                margin: 10px auto;
            }

            .table img {
                width: 40px;
                height: 40px;
            }
        </style>
    </head>

    <body>
        <div class="container">
            <div class="panel panel-primary">
                <!-- Default panel contents -->
                <div class="panel-heading">英雄列表管理</div>
                <div class="panel-body">
                    <!-- 存放的搜索区域 -->
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="input-group">
                                <input type="text" id="hname" class="form-control" placeholder="输入英雄信息..." autocomplete="true" />
                                <span class="input-group-btn">
                                    <button class="btn btn-default" id="btn_search" type="button">搜索</button>
                                </span>
                            </div>
                            <!-- /input-group -->
                        </div>
                        <!-- /.col-lg-6 -->

                        <div class="col-lg-3 col-lg-offset-3">
                            <!-- 添加英雄的按钮 -->
                            <!-- data-toggle="modal":说明控制显示隐藏的元素是toggle效果 -->
                            <!-- data-target:控制的模态框是#myModal -->
                            <!-- 属性的方式只能简单的弹出模态框,不能进行其它的业务处理 -->
                            <button type="button" class="btn btn-success openDialog">添加英雄</button>
                        </div>
                    </div>
                </div>

                <!-- Table -->
                <table class="table">
                    <thead>
                        <tr>
                            <th>编号</th>
                            <th>英雄名称</th>
                            <th>英雄性别</th>
                            <th>头像</th>
                            <th>操作区</th>
                        </tr>
                    </thead>
                    <!-- 表格主体 -->
                    <tbody id="tbody"></tbody>
                </table>
            </div>
        </div>

        <!-- 创建模板引擎结构 -->
        <script type="text/template" id="heroListTemp">
              {{each data v i}}
              <tr>
                <td>{{i + 1}}</td>
                <td>{{v.name}}</td>
                <td>{{v.gender}}</td>
                <td>
                    <img src="{{v.img}}" alt="" />
                </td>
                <td>
                    <button type="button" class="btn btn-danger">删除</button>
                </td>
            </tr>
              {{/each}}
        </script>

        <script src="./libs/jquery/jquery.min.js"></script>
        <script src="./libs/bootstrap/js/bootstrap.min.js"></script>
        <!-- 引入模板引擎js -->
        <script src="./libs/template-web.js"></script>
    </body>
    <script>
        $(function () {
            function init() {
                let userKey = $('#hname').val().trim();
                console.log(userKey);

                $.ajax({
                    type: 'get',
                    url: 'http://127.0.0.1:3001/getHeroList',
                    data: { heroName: userKey },
                    success: res => {
                        console.log(res);
                        // 调用模板引擎
                        let html = template('heroListTemp', res);
                        $('#tbody').html(html);
                    },
                });
            }
            init();
        });
    </script>
</html>

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Henry_ww

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值