Python学习第162天(删除按钮bug修复、编辑模态对话框形式展现)

一、上一篇初步完成了删除按钮的模态对话框形式,但是存在一个问题,该删除按钮是在网页第一次加载之后完成渲染,对于使用模态对话框新增部分的信息,如果未能刷新,则通过模态对话框增加部分的删除按钮是没有进行渲染的,所以此时如果想删除刚增加的内容就必须刷新。

 

 此时我们引入新的绑定方法,针对一个标签,只有我们点击的时候才会触发。

 

 关于删除键的其他案件功能和方式并没有发生变化,这里需要特别注意的一个问题就是,为此我检查了两个多小时

 

 

二、下面来说一下编辑功能的实现,编辑功能的模态对话框其实可以完全使用新增功能的,但是难点在于让输入框内显示需要修改的学生的原始信息,大致分为以下几步:

  (一)给每行信息设定相应的自定义变量,便于后期得到数值后进行赋值操作

  

 

   (二)对数据进行获取,并将对应input框name属性设置和上面所设置的na自定义属性值相同

  

 

   

 

   

 

   (三)关于后台部分的内容

  

 

   大致步骤就是以上这些,下面要说一下关于ajax的两个新知识,一个是dataType属性,通过设置他为JSON,可以默认对传输回来的json数据完成JSON.parse(arg)操作

  另一个是关于在传输字典时k,v中v的值如果是列表或字典该如何进行操作

    1.如果是列表,需要增加traditional:true的属性设置,即可

    2.如果是字典

 $.ajax({
                url: 'http//www.baidu.com',
                type: 'GET',
                data: {'k1': JSON.stringify({}) },
                dataType: 'JSON',
                success:function(arg){
                    // arg是对象
                }
            })

    我们可以先将v值的字典转换为字符串形式(通过JSON.stringify({ }) ),然在后台获取之后,通过json.loads()重新获取到

下面是这两天的成果:

url:

    re_path('^add_student.html',students.add_student),
    re_path('^del_student.html',students.del_student),
    re_path('^edit_student.html',students.edit_student)

get_students.html(正好400行,开心):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css">
    <style>
        .bbq {
            padding: 0px 20px;
            font-size: 15px;
        }

        #delNid {
            font-size: large;
        }

        #nothing {
            color: #0f0f0f;
        }
    </style>
</head>
<body>
<div class="container">
    <div style="padding: 10px 0px">
        <a class="btn btn-info" href="add_students.html">添加学生</a>
        <a class="btn btn-info" id="addBtn">添加学生(新)</a>
    </div>
    <div>
        <table class="table table-hover table-striped" border="1">
            <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>班级</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="tb">
            {% for row in stu_list %}
                <tr nid="{{ row.id }}" n_name="{{ row.username }}" class="">
                    <td na="nid">{{ row.id }}</td>
                    <td na="user">{{ row.username }}</td>
                    <td na="age">{{ row.age }}</td>
                    <td na="gender" gid="{{ row.gender }}">
                        {% if row.gender %}
                            男
                        {% else %}
                            女
                        {% endif %}
                    </td>
                    <td na="cs_id" cid="{{ row.cs_id }}">{{ row.cs.titile }}</td>
                    <td>
                        <a class="glyphicon glyphicon-remove bbq del-row">删除</a>
                        <a class="glyphicon glyphicon-wrench bbq edit-row">编辑</a>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>

    <!-- addModal -->
    <div class="modal fade" id="addModal" 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">添加学生</h4>
                </div>
                <div class="modal-body">

                    <form class="form-horizontal">
                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="username" placeholder="姓名">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="age" id="age_message" placeholder="年龄">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="1"></label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="0"></label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">班级</label>
                            <div class="col-sm-10">
                                <select class="form-control" name="cs_id">
                                    <option value="1">
                                        {% for row in cs_list %}
                                            <option value="{{ row.id }}">{{ row.titile }}</option>
                                        {% endfor %}
                                </select>
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <span style="color: red" id="errorMessage"></span>
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btnSave">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- delModal -->
    <div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="alert alert-danger" role="alert">
                <h3>确认删除学生信息</h3>
                <div id="delNid" style="display: inline"></div>
                <div id="nothing" style="display: inline">信息删除后将无法恢复!!!</div>
                <div>
                    <button type="button" id="delConfirm" class="btn btn-danger">确定</button>
                    <button type="button" class="btn btn-success" id="quitDel">取消</button>
                </div>
            </div>
        </div>
    </div>

    <!-- editModal -->
    <div class="modal fade" id="editModal" 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">编辑学生信息</h4>
                </div>
                <div class="modal-body">

                    <form class="form-horizontal">
                        <input type="text" name="nid" style="display: none">

                        <div class="form-group">
                            <label for="username" class="col-sm-2 control-label">姓名</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="user" placeholder="姓名">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">年龄</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" name="age" id="age_message" placeholder="年龄">
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">性别</label>
                            <div class="col-sm-10">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="1"></label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="0"></label>
                            </div>
                        </div>

                        <div class="form-group">
                            <label for="age" class="col-sm-2 control-label">班级</label>
                            <div class="col-sm-10">
                                <select class="form-control" name="cs_id">
                                    <option value="1">
                                        {% for row in cs_list %}
                                            <option value="{{ row.id }}">{{ row.titile }}</option>
                                        {% endfor %}
                                </select>
                            </div>
                        </div>
                    </form>

                </div>
                <div class="modal-footer">
                    <span style="color: red" id="errorMessage"></span>
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="btnEditSave">保存</button>
                </div>
            </div>
        </div>
    </div>

    <script src="/static/js/jquery-3.1.1.js"></script>
    <script src="/static/plugins/bootstrap/js/bootstrap.js"></script>
    <script>
        $(function () {
            bindEvent();
            bindSave();
            bindDel();
            bindDelConfirm();
            bindQuit();
            bindEdit();
            bindEditConfirm();
        });
        //编辑学生信息确认
        function bindEditConfirm() {
            $('#btnEditSave').click(function () {
                var postData = {};
                $('#editModal').find('input,select').each(function () {
                    console.log($(this)[0]);
                    var v = $(this).val();
                    var n = $(this).attr('name');
                    if (n == 'gender') {
                        if ($(this).prop('checked')) {
                            postData[n] = v;
                        }
                    } else {
                        postData[n] = v;
                    }
                })
                $.ajax({
                    url:'/edit_student.html/',
                    type:'POST',
                    data:postData,
                    success:function (arg) {
                        var n = JSON.parse(arg)
                        if (n.status){
                            window.location.reload()
                        }else {
                            alert(n.error)
                        }
                    }
                    })
            })
        }
        
        //编辑学生信息显示
        function bindEdit() {
            $('#tb').on('click','.edit-row',function () {
                $('#editModal').modal('show');
                //显示后需要获取当前行的所有数据
                //此时点击标签的父集之前的所有数据,可以通过prevAll()获取
                $(this).parent().prevAll().each(function () {
                    var v = $(this).text();
                    var n = $(this).attr('na');
                    console.log(n)
                    if (n=='cs_id'){
                        var cid = $(this).attr('cid');
                        $('#editModal select[name="cs_id"]').val(cid);
                        console.log("设置班级")
                    }else if(n=='gender'){
                        var gid = $(this).attr('gid');
                        console.log('设置性别',gid)
                        if(gid=='True'){
                            $('#editModal :radio[value="1"]').prop('checked',true);
                            console.log('是个男的')
                        }else{
                            $('#editModal :radio[value="0"]').prop('checked',true);
                        }
                    }else {
                        $("#editModal input[name='"+ n +"']").val(v)
                    }
                })
            })
        }

        function bindQuit() {
            $('#quitDel').click(function () {
                $('#delModal').modal('hide')
            })
        }

        function bindDelConfirm() {
            $('#delConfirm').click(function () {
                var rowId = $('#delNid').val();
                console.log(rowId)
                $.ajax({
                    url: '/del_student.html',
                    type: 'GET',
                    data: {'nid': rowId},
                    success: function (arg) {
                        var dict = JSON.parse(arg);
                        if (dict.status) {
                            $('tr[nid="' + rowId + '"]').remove();
                            $('#delModal').modal('hide');
                        }
                    }
                })
            })

        }

        function bindDel() {
            $('#tb').on('click','.del-row',function () {
                //此时因为弹窗跳出,弹窗内无法获得需要删除学生信息的id
                //所以在表格的tr标签内设置自定义变量 nid = {{ row.id }}
                //从而方便本次弹窗跳出事件后获得对应的id信息
                var rowId = $(this).parent().parent().attr('nid');
                var rowName = $(this).parent().parent().attr('n_name');
                console.log(rowId)
                $('#delNid').val(rowId);
                $('#delNid').text(rowName);
                $('#delModal').modal('show');
            })
        }

        function bindEvent() {
            $('#addBtn').click(function () {
                $('#addModal').modal('show');
            })
        }

        function bindSave() {
            $('#btnSave').click(function () {
                var postData = {};//关于postData,当点击“保存”按钮之后,
                                  //postData就成为{'username':'二百五','age':18,'gender':1,'cs_id':2}
                                  //类似以上这样的一个字典,而表格中的id等于后台返回的JSON.parse(arg).data
                $('#addModal').find('input,select').each(function () {
                    console.log($(this)[0]);
                    var v = $(this).val();
                    var n = $(this).attr('name');
                    if (n == 'gender') {
                        if ($(this).prop('checked')) {
                            postData[n] = v;
                        }
                    } else {
                        postData[n] = v;
                    }
                })
                console.log(postData)
                $.ajax({
                    url: '/add_student.html',
                    type: 'POST',
                    data: postData,
                    success: function (arg) {
                        console.log(arg);
                        var dict = JSON.parse(arg);
                        if (dict.status) {
                            //window.location.reload()  此时不利用刷新来实现添加成功,避免流量和计算的浪费
                            createRow(postData, dict.data);
                            $('#addModal').modal('hide');
                        } else {
                            $('#errorMessage').text(dict.message)
                        }
                    }
                })
            })
        }

        function createRow(postData, nid) {
            var tr = document.createElement('tr');
            $(tr).attr('nid',nid);
            $(tr).attr('n_name',postData.username);
            var tdId = document.createElement('td');
            tdId.innerHTML = nid;
            $(tr).append(tdId);
            var tdUsername = document.createElement('td');
            tdUsername.innerHTML = postData.username;
            $(tr).append(tdUsername);
            var tdAge = document.createElement('td');
            tdAge.innerHTML = postData.age;
            $(tr).append(tdAge);

            var tdGender = document.createElement('td');
            if (postData.gender == '0') {
                tdGender.innerHTML = '';
            } else {
                tdGender.innerHTML = '';
            }
            $(tr).append(tdGender);

            var tdClass = document.createElement('td');
            var textClass = $('select[name="cs_id"]').find('option[value="' + postData.cs_id + '"]').text();
            tdClass.innerHTML = textClass
            $(tr).append(tdClass)

            var tdHandle = '<td><a class="glyphicon glyphicon-remove bbq del-row">删除</a>' +
                           '<a class="glyphicon glyphicon-wrench bbq edit-row">编辑</a><td>'
            $(tr).append(tdHandle)

            $('#tb').append(tr)
            console.log($(tr).attr('nid'))
            console.log($(tr).attr('n_name'))
        }

    </script>

</div>
</body>
</html>

students.py

def add_student(req):
    respon = {'status':True,'message':None,'data':None}
    try:
        u = req.POST.get('username')
        a = req.POST.get('age')
        g = req.POST.get('gender')
        c = req.POST.get('cs_id')
        print(u, a, g, c)
        obj = models.Students.objects.create(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
        respon['data'] = obj.id
    except Exception as e:
        respon['status'] = False
        respon['message'] = '用户输入信息格式错误'
    import json
    result = json.dumps(respon,ensure_ascii=False)
    return HttpResponse(result)

def del_student(req):
    ret = {'status':True}
    try:
        nid = req.GET.get('nid')
        models.Students.objects.filter(id=nid).delete()
    except Exception as e:
        ret['status'] = False
    import json
    return HttpResponse(json.dumps(ret))

def edit_student(req):
    response = {'status':True,'error':None}
    try:
        nid = req.POST.get('nid')
        u = req.POST.get('user')
        a = req.POST.get('age')
        g = req.POST.get('gender')
        c = req.POST.get('cs_id')
        models.Students.objects.filter(id=nid).update(
            username=u,
            age=a,
            gender=g,
            cs_id=c
        )
    except Exception as e:
        response['status'] = False
        response['error'] = '输入信息格式错误'
    import json
    return HttpResponse(json.dumps(response))

以上就是今天的内容。

 

posted @ 2020-09-24 22:38  崆峒山肖大侠  阅读(227)  评论(0编辑  收藏  举报