day91-django学生列表之增删改查(模态框-ajax提交)
1.urls.py from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('add_model/', views.add_model), path('del_model/', views.del_model), path('edit_model/', views.edit_model), ] 2.sqlhelper.py import pymysql def get_list(sql,args): conn = pymysql.connect( host='localhost', port=3306, user='root', password='123', database='django_test', charset='utf8' ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql,args) result = cursor.fetchall() cursor.close() conn.close() return result def get_one(sql,args): conn = pymysql.connect( host='localhost', port=3306, user='root', password='123', database='django_test', charset='utf8' ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql,args) result = cursor.fetchone() cursor.close() conn.close() return result def modify(sql,args): conn = pymysql.connect( host='localhost', port=3306, user='root', password='123', database='django_test', charset='utf8' ) cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) cursor.execute(sql,args) conn.commit() cursor.close() conn.close() 3.views.py from app01 import sqlhelper from django.shortcuts import render,redirect,HttpResponse import json #学生列表 def students(request): result = sqlhelper.get_list('select students.id,students.name,students.class_id,classes.title from students left join classes on students.class_id = classes.id',[]) classes = sqlhelper.get_list('select id,title from classes',[]) return render(request,'students.html',{'result':result,'classes':classes}) #添加 def add_model(request): name = request.POST.get('name') class_id = request.POST.get('class_id') if name.strip(): sqlhelper.modify('insert into students(name,class_id) values(%s,%s)', [name, class_id]) return HttpResponse('ok') else: return HttpResponse('not ok') #删除 def del_model(request): ret = {'status':True,'message':None} nid = request.POST.get('nid') try: sqlhelper.modify('delete from students where id=%s',[nid]) except Exception as e:#尝试执行,如果有问题就把异常放在e里面 ret['status'] = False ret['message'] = str(e) #HttpResponse只能返回字符串,json.dumps(ret)字典转为字符串(序列化) return HttpResponse(json.dumps(ret)) #编辑 def edit_model(request): nid = request.POST.get('id') name = request.POST.get('name') class_id = request.POST.get('class_id') if name.strip(): sqlhelper.modify('update students set name=%s,class_id=%s where id=%s',[name,class_id,nid]) return HttpResponse('ok') else: return HttpResponse('not ok')
students.html
<body> <h1>学生列表</h1> <a href="/add_student/">添加</a> <input type="button" value="模态框添加" id="add_model"> <table border="1"> <thead> <tr> <th>id</th> <th>name</th> <th>title</th> <th>操作</th> </tr> </thead> <tbody> {% for row in result %} <tr> <td>{{ row.id }}</td> <td>{{ row.name }}</td> <td cls_id = '{{ row.class_id }}'>{{ row.title }}</td><!--cls_id是自定义属性--> <td> <a href="/edit_student/?nid={{ row.id }}">编辑</a> | <a href="/del_student/?nid={{ row.id }}">删除</a> | <input type="button" value="模态框编辑" id="edit_model"> | <input type="button" value="模态框删除" id="del_model"> </td> </tr> {% endfor %} </tbody> </table> {#遮罩层#} <div class="shadow hide"></div> {#模态框添加#} <div class="model hide"> <h1>添加学生</h1> <p>姓名: <input type="text" id="add_name"> </p> <p>班级: <select id="add_class"> {% for row in classes %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> </p> <p> <input type="button" value="提交" id="add_send"> <input type="button" value="取消" id="add_cancel"> </p> </div> {#模态框编辑#} <div class="e_model hide"> <h1>编辑学生</h1> <p>姓名: <input type="text" id="edit_name"> <span style="color:red" id="edit_error"></span>
<!--隐藏学生id,通过js获取当前编辑行的id,用于提交-->
<input type="text" id="edit_id" style="display: none"> </p> <p>班级: <select id="edit_class"> {% for row in classes %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> </p> <p> <input type="button" value="提交" id="edit_send"> <input type="button" value="取消" id="edit_cancel"> </p> </div> <script src="../static/jquery-3.4.1.min.js"></script> <script> /************************模态框添加*************************/ //点模态框添加,弹出模态框 $('#add_model').on('click', function () { $('.shadow,.model').removeClass('hide') });
//点模态框里的取消,隐藏模态框 $('#add_cancel').on('click', function () { $('.shadow,.model').addClass('hide') });
//点模态框里的提交,触发ajax事件,提交数据,接着拿到返回的数据。 //把data以POST的类型通过这个地址发送给服务器,服务器处理成功后,启动函数处理返回的数据。 //location.reload()是跳到当前页面,也就是/students/页面。 $('#add_send').on('click', function () { var name = $('#add_name').val(); var class_id = $('#add_class').val(); $.ajax({ url: '/add_model/', type: 'POST', data: {'name': name, 'class_id': class_id}, success: function (data) { if (data == 'ok') { location.reload() } else { alert('姓名不能为空') } } }) }); /************************模态框删除*************************/ //如果通过id找不到该标签,在前面加上父标签 $('tbody #del_model').on('click', function () { //找到当前对象的父对象的前面的所有对象 var $ele = $(this).parent().prevAll(); //拿到id var nid = $($ele[2]).text(); $.ajax({ url: '/del_model/', type: 'POST', data: {'nid': nid}, success: function (data) { data = JSON.parse(data); if (data.status) { location.reload() } else { alert(data.message) } } }) }); /************************模态框编辑*************************/ //点模态框编辑 $('tbody #edit_model').on('click', function () { //弹出模态框 $('.shadow,.e_model').removeClass('hide'); //找到当前对象的父对象的前面的所有对象 var $ele = $(this).parent().prevAll(); //找到编辑的当前行的姓名 var name = $($ele[1]).text(); //找到编辑的当前行的班级id var classId = $($ele[0]).attr('cls_id');//cls_id是自定义属性 //找到编辑的当前行的学生id var id = $($ele[2]).text(); //把当前行的姓名当做默认值设置到模态框里 $('#edit_name').val(name); //把当前行的班级id当做默认值设置到模态框里,班级名称自动与之对应上。 $('#edit_class').val(classId); //把当前行的学生id当做默认值设置到模态框里,隐藏起来,提交的时候需要用到 $('#edit_id').val(id); });
//点模态框的取消,隐藏模态框 $('#edit_cancel').on('click', function () { $('.shadow,.e_model').addClass('hide') });
//点模态框的提交 $('#edit_send').on('click',function () { var id = $('#edit_id').val(); var name = $('#edit_name').val(); var classId = $('#edit_class').val(); $.ajax({ url:'/edit_model/', type:'POST', data:{'id':id,'name':name,'class_id':classId}, success:function (data) { if(data=='ok'){location.reload()}else{$('#edit_error').text('姓名不能为空')} } }) }) </script> </body>