s4 学员管理示例
- django示例:学员管理
# 单表操作:URL跳转添加、删除、编辑
# pymysql操作数据库,
# 一对多操作:URL跳转添加
# pymysql操作数据库组件
# Ajax单表添加
# Ajax单表编辑
# Ajax一对多添加
# Ajax一对多编辑
# 多对多查看
# 多对多:URL添加、编辑
# 多对多:ajax添加(js获取列表、加载框)、编辑(未实现)
# 编辑思路:[11,22,33].indexOf(22222)
# bootstrip应用
# 后台管理布局示例
# day68代码
# 学员管理-表结构
班级表:
id title
1 全栈4期
2 全栈5期
学生表:
id name 班级ID(FK)
1 张英杰 1
老师表:
id name
1 林海峰
2 林狗
3 苑日天
老师班级关系表:
id 老师ID 班级ID
1 1 1
2 1 2
3 2 2
# 单表操作
# 一对多操作
# 多对多操作
<p>所属班级
<select name="class_id">
{% for row in class_list %}
{% if row.id == current_student_info.id %}
<option selected value="{{ row.id }}">{{ row.title }}</option>
{% else %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endif %}
{% endfor %}
</select>
</p>
- urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
# url(r'^admin/', admin.site.urls),
url(r'^classes/', views.classes),
url(r'^add_class/', views.add_class),
url(r'^del_class/', views.del_class),
url(r'^edit_class/', views.edit_class),
url(r'^students/', views.students),
url(r'^add_student/', views.add_student),
url(r'^edit_student/', views.edit_student),
url(r'^modal_add_class/', views.modal_add_class),
url(r'^modal_edit_class/', views.modal_edit_class),
url(r'^modal_add_student/', views.modal_add_student),
url(r'^modal_edit_student/', views.modal_edit_student),
url(r'^teachers/', views.teachers),
url(r'^add_teacher/', views.add_teacher),
url(r'^edit_teacher/', views.edit_teacher),
url(r'^get_all_class/', views.get_all_class),
url(r'^modal_add_teacher/', views.modal_add_teacher),
]
- utils/sqlheper.py
import pymysql
def get_list(sql,args):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', 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='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', 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='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql,args)
conn.commit()
cursor.close()
conn.close()
def create(sql,args):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(sql,args)
conn.commit()
last_row_id = cursor.lastrowid
cursor.close()
conn.close()
return last_row_id
class SqlHelper(object):
def __init__(self):
# 读取配置文件
self.connect()
def connect(self):
self.conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
def get_list(self,sql,args):
self.cursor.execute(sql,args)
result = self.cursor.fetchall()
return result
def get_one(self,sql,args):
self.cursor.execute(sql,args)
result = self.cursor.fetchone()
return result
def modify(self,sql,args):
self.cursor.execute(sql,args)
self.conn.commit()
def multiple_modify(self,sql,args):
# self.cursor.executemany('insert into bd(id,name)values(%s,%s)',[(1,'alex'),(2,'eric')])
self.cursor.executemany(sql,args)
self.conn.commit()
def create(self,sql,args):
self.cursor.execute(sql,args)
self.conn.commit()
return self.cursor.lastrowid
def close(self):
self.cursor.close()
self.conn.close()
- views.py
from django.shortcuts import render, redirect,HttpResponse
import pymysql
import json
def classes(request):
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,title from class")
class_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request, 'classes.html', {'class_list': class_list})
def add_class(request):
if request.method == "GET":
return render(request, 'add_class.html')
else:
print(request.POST)
v = request.POST.get('title')
if len(v) > 0:
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into class(title) values(%s)", [v, ])
conn.commit()
cursor.close()
conn.close()
return redirect('/classes/')
else:
return render(request, 'add_class.html',{'msg':'班级名称不能为空'})
def del_class(request):
nid = request.GET.get('nid')
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("delete from class where id=%s", [nid, ])
conn.commit()
cursor.close()
conn.close()
return redirect('/classes/')
def edit_class(request):
if request.method == "GET":
nid = request.GET.get('nid')
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,title from class where id = %s", [nid, ])
result = cursor.fetchone()
cursor.close()
conn.close()
print(result)
return render(request, 'edit_class.html', {'result': result})
else:
nid = request.GET.get('nid')
title = request.POST.get('title')
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("update class set title=%s where id = %s", [title, nid, ])
conn.commit()
cursor.close()
conn.close()
return redirect('/classes/')
def students(request):
"""
学生列表
"""
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute(
"select student.id,student.name,student.class_id,class.title from student left JOIN class on student.class_id = class.id")
student_list = cursor.fetchall()
cursor.close()
conn.close()
class_list = sqlheper.get_list('select id,title from class',[])
return render(request, 'students.html', {'student_list': student_list,'class_list':class_list})
def add_student(request):
if request.method == "GET":
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("select id,title from class")
class_list = cursor.fetchall()
cursor.close()
conn.close()
return render(request, 'add_student.html', {'class_list': class_list})
else:
name = request.POST.get('name')
class_id = request.POST.get('class_id')
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='', db='s4db65', charset='utf8')
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
cursor.execute("insert into student(name,class_id) values(%s,%s)", [name, class_id, ])
conn.commit()
cursor.close()
conn.close()
return redirect('/students/')
from utils import sqlheper
def edit_student(request):
if request.method == "GET":
nid = request.GET.get('nid')
class_list = sqlheper.get_list("select id,title from class",[])
current_student_info = sqlheper.get_one('select id,name,class_id from student where id=%s',[nid,])
return render(request,'edit_student.html',{'class_list': class_list,'current_student_info':current_student_info})
else:
nid = request.GET.get('nid')
name = request.POST.get('name')
class_id = request.POST.get('class_id')
sqlheper.modify('update student set name=%s,class_id=%s where id=%s',[name,class_id,nid,])
return redirect('/students/')
# 对话框
def modal_add_class(request):
title = request.POST.get('title')
if len(title) > 0:
sqlheper.modify('insert into class(title) values(%s)',[title,])
return HttpResponse('ok')
else:
return HttpResponse('班级标题不能为空')
def modal_edit_class(request):
ret = {'status': True, 'message':None}
try:
nid = request.POST.get('nid')
content = request.POST.get('content')
sqlheper.modify('update class set title=%s where id=%s',[content,nid,])
except Exception as e:
ret['status'] = False
ret['message'] = "处理异常"
return HttpResponse(json.dumps(ret))
def modal_add_student(request):
ret = {'status': True,'message': None}
try:
name = request.POST.get('name')
class_id = request.POST.get('class_id')
sqlheper.modify('insert into student(name,class_id) values(%s,%s)',[name,class_id,])
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
def modal_edit_student(request):
ret = {'status': True,'message': None}
try:
nid = request.POST.get('nid')
name = request.POST.get('name')
class_id = request.POST.get('class_id')
sqlheper.modify('update student set name=%s,class_id=%s where id=%s',[name,class_id,nid,])
except Exception as e:
ret['status'] = False
ret['message'] = str(e)
return HttpResponse(json.dumps(ret))
# 多对多,以老师表展示
def teachers(request):
# teacher_list = sqlheper.get_list('select id,name from teacher',[])
teacher_list = sqlheper.get_list("""
select teacher.id as tid,teacher.name,class.title from teacher
LEFT JOIN teacher2class on teacher.id = teacher2class.teacher_id
left JOIN class on class.id = teacher2class.class_id;
""",[])
print(teacher_list)
result = {}
for row in teacher_list:
tid =row['tid']
if tid in result:
result[tid]['titles'].append(row['title'])
else:
result[tid] = {'tid': row['tid'],'name':row['name'],'titles': [row['title'],]}
return render(request,'teacher.html',{'teacher_list':result.values()})
def add_teacher(request):
if request.method == "GET":
class_list = sqlheper.get_list('select id,title from class',[])
return render(request,'add_teacher.html',{'class_list': class_list})
else:
name = request.POST.get('name')
# 老师表中添加一条数据
teacher_id = sqlheper.create('insert into teacher(name) values(%s)',[name,])
# 老师和班级关系表中插入数据
# ['3', '4', '5', '6', '7']
# 获取当前添加的老师id=2
# 23
# 24
#
class_ids = request.POST.getlist('class_ids')
# 多次连接,多次提交
# for cls_id in class_ids:
# sqlheper.modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',[teacher_id,cls_id,])
# 连接一次,多次提交
# obj = sqlheper.SqlHelper()
# for cls_id in class_ids:
# obj.modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',[teacher_id,cls_id,])
# obj.close()
# 一次连接,一次提交
data_list = []
for cls_id in class_ids:
temp = (teacher_id,cls_id,)
data_list.append(temp)
obj = sqlheper.SqlHelper()
obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
obj.close()
return redirect('/teachers/')
def edit_teacher(request):
if request.method == "GET":
nid = request.GET.get('nid')
obj = sqlheper.SqlHelper()
teacher_info = obj.get_one('select id,name from teacher where id =%s',[nid,])
class_id_list = obj.get_list('select class_id from teacher2class where teacher_id=%s',[nid,])
class_list = obj.get_list('select id,title from class',[])
obj.close()
print('当前老师信息',teacher_info)
print('当前老师任教的班级id',class_id_list)
temp = []
for i in class_id_list:
temp.append(i['class_id'])
print('所有班级',class_list)
# return HttpResponse('...')
return render(request,'edit_teacher.html',{
'teacher_info': teacher_info,
'class_id_list': temp,
'class_list': class_list,
})
else:
nid = request.GET.get('nid')
name = request.POST.get('name')
class_ids = request.POST.getlist('class_ids')
obj = sqlheper.SqlHelper()
# 更新老师表
obj.modify('update teacher set name=%s where id=%s',[name,nid])
# 更新老师和班级关系表
# 先把当前老师和班级的对应关系删除,然后再添加
obj.modify('delete from teacher2class where teacher_id=%s',[nid,])
data_list = []
for cls_id in class_ids:
temp = (nid,cls_id,)
data_list.append(temp)
# map?lambda表达式?
obj = sqlheper.SqlHelper()
obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
obj.close()
return redirect('/teachers/')
def get_all_class(request):
obj = sqlheper.SqlHelper()
class_list = obj.get_list('select id,title from class',[])
obj.close()
return HttpResponse(json.dumps(class_list))
def modal_add_teacher(request):
ret = {'status': True,'message': None}
try:
name = request.POST.get('name')
class_id_list = request.POST.getlist('class_id_list')
teacher_id = sqlheper.create('insert into teacher(name) values(%s)',[name,])
data_list = []
for cls_id in class_id_list:
temp = (teacher_id,cls_id,)
data_list.append(temp)
obj = sqlheper.SqlHelper()
obj.multiple_modify('insert into teacher2class(teacher_id,class_id) values(%s,%s)',data_list)
obj.close()
except Exception as e:
ret['status'] = False
ret['message'] = "处理失败"
return HttpResponse(json.dumps(ret))
- classes.html
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css" />
<link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css" />
<style>
.hide{
display: none;
}
.shadow{
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: black;
opacity: 0.4;
z-index: 999;
}
.modal{
z-index: 1000;
position: fixed;
left: 50%;
top: 50%;
height: 300px;
width: 400px;
background-color: white;
margin-left: -200px;
margin-top: -150px;
}
</style>
</head>
<body>
<div style="width: 700px;margin: 0 auto;">
<h1>班级列表</h1>
<div style="margin: 10px 0;">
<a class="btn btn-primary" href="/add_class/">添加</a>
<a class="btn btn-info" onclick="showModal();">对话框添加</a>
</div>
<table class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>ID</th>
<th>班级名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for row in class_list %}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.title }}</td>
<td>
<a class="glyphicon glyphicon-pencil" href="/edit_class/?nid={{ row.id }}"></a>
|
<a class="fa fa-battery-full" onclick="modelEdit(this);"></a>
|
<a class="glyphicon glyphicon-trash" href="/del_class/?nid={{ row.id }}"></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div id="shadow" class="shadow hide"></div>
<div id="modal" class="modal hide">
<p>
<input id="title" type="text" name="title" />
</p>
<input type="button" value="提交" onclick="AjaxSend();" /><span id="errormsg"></span>
<input type="button" value="取消" onclick="cancleModal();" />
</div>
<div id="editModal" class="modal hide">
<h3>编辑框</h3>
<p>
<input id="editId" type="text" name="id" style="display: none" />
<input id="editTitle" type="text" name="title" />
</p>
<input type="button" value="提交" onclick="editAjaxSend();" /><span id="errormsg"></span>
<input type="button" value="取消" onclick="cancleModal();" />
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
function showModal(){
document.getElementById('shadow').classList.remove('hide');
document.getElementById('modal').classList.remove('hide');
}
function cancleModal(){
document.getElementById('shadow').classList.add('hide');
document.getElementById('modal').classList.add('hide');
document.getElementById('editModal').classList.add('hide');
}
function AjaxSend(){
$.ajax({
url: '/modal_add_class/',
type: 'POST',
data: {'title': $('#title').val()},
success: function(data){
// 当服务端处理完成后,返回数据时,该函数自动调用
// data=服务端返回的值
console.log(data);
if(data == "ok"){
location.href= "/classes/";
}else{
$('#errormsg').text(data);
}
}
})
}
function modelEdit(ths){
document.getElementById('shadow').classList.remove('hide');
document.getElementById('editModal').classList.remove('hide');
/*
1. 获取当前点击标签
2. 当前标签父标签,再找其上方标签
3. 获取当前行班级名称,赋值到编辑对话框中
*/
var row = $(ths).parent().prevAll();
var content = $(row[0]).text();
$('#editTitle').val(content);
var contentId = $(row[1]).text();
$('#editId').val(contentId);
}
function editAjaxSend(){
var nid = $('#editId').val();
var content = $('#editTitle').val();
$.ajax({
url:'/modal_edit_class/',
type: 'POST',
data: {'nid':nid, 'content': content},
success:function(arg){
// arg字符串类型
// JSON.parse(字符串) => 对象
// JSON.stringify(对象) => 字符串
arg = JSON.parse(arg);
if(arg.status){
// location.href = "/classes/"
location.reload();
}else{
alert(arg.message);
}
}
})
}
</script>
</body>
- add_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>添加班级</h1>
<form method="POST" action="/add_class/">
<p>班级名称:<input type="text" name="title" /></p>
<input type="submit" value="提交" />{{ msg }}
</form>
</body>
</html>
- edit_class.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>编辑班级</h1>
<form method="POST" action="/edit_class/?nid={{ result.id }}">
<p>班级名称:<input type="text" name="title" value="{{ result.title }}" /></p>
<input type="submit" value="提交" />
</form>
</body>
</html>
- student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.hide{
display: none;
}
.shadow{
/*相对于窗口*/
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
opacity: 0.4;
z-index: 999;
}
.add-modal{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 300px;
z-index: 1000;
background-color: white;
margin-left: -200px;
margin-top: -200px;
}
</style>
</head>
<body>
<h1>学生列表</h1>
<div>
<a href="/add_student/">添加</a>
<a id="addModal">对话框添加</a>
</div>
<table>
<thead>
<tr>
<th>ID</th>
<th>学生姓名</th>
<th>所属班级</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for row in student_list %}
<tr>
<td>{{ row.id }}</td>
<td>{{ row.name }}</td>
<td clsId="{{ row.class_id }}">{{ row.title }}</td>
<td>
<a href="/edit_student/?nid={{ row.id }}">编辑</a>
|
<a class="btn-edit">对话框编辑</a>
|
<a>删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow" class="shadow hide"></div>
<div id="addModal" class="add-modal hide">
<p>
姓名:<input id="addName" type="text" name="name" placeholder="姓名" />
</p>
<p>
班级:
<select id="addClassId" name="classId">
{% for row in class_list %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input id="btnAdd" type="button" value="添加" />
<span id="addError" style="color: red;"></span>
</div>
<div id="editModal" class="add-modal hide">
<h3>编辑学生信息</h3>
<p>
姓名:<input id="editName" type="text" name="name" placeholder="姓名" />
<input type="text" id="editId" style="display: none" />
</p>
<p>
班级:
<select id="editClassId" name="classId">
{% for row in class_list %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input id="btnEdit" type="button" value="更新" />
<span id="editError" style="color: red;"></span>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
$(function(){
$('#addModal').click(function(){
$('#shadow,#addModal').removeClass('hide');
});
$('#btnAdd').click(function(){
$.ajax({
url: '/modal_add_student/',
type: 'POST',
data: {'name': $('#addName').val(), 'class_id': $('#addClassId').val()},
success:function(arg){
arg = JSON.parse(arg);
if(arg.status){
location.reload();
}else{
$('#addError').text(arg.message);
}
}
})
});
$('.btn-edit').click(function(){
$('#shadow,#editModal').removeClass('hide');
/*
1. 获取当前标签,$(this)
*/
var tds = $(this).parent().prevAll();
var studentId = $(tds[2]).text();
var studentName = $(tds[1]).text();
var classId = $(tds[0]).attr('clsid');
console.log(studentId,studentName,classId);
$('#editId').val(studentId);
$('#editName').val(studentName);
$('#editClassId').val(classId);
});
$('#btnEdit').click(function(){
$.ajax({
url:'/modal_edit_student/',
type: 'POST',
data: {'nid': $('#editId').val(), 'name':$('#editName').val(),'class_id': $('#editClassId').val()},
dataType: 'JSON', //JSON.parse(arg)
success:function(arg){
if(arg.status){
location.reload();
}else{
$('#editError').text(arg.message);
}
}
})
})
})
</script>
</body>
</html>
- add_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>添加学生</h1>
<form method="POST" action="/add_student/">
<p>学生姓名<input type="text" name="name" /></p>
<p>
所属班级
<select name="class_id">
{% for row in class_list %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endfor %}
</select>
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
- edit_student.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>编辑学生</h1>
<form method="POST" action="/edit_student/?nid={{ current_student_info.id }}">
<p>学生姓名<input type="text" name="name" value="{{ current_student_info.name }}" /></p>
<p>
所属班级
<select name="class_id">
<!-- 循环所有的班级 -->
{% for row in class_list %}
<!-- 如果是当前学生所在班级,则默认选中 -->
{% if row.id == current_student_info.class_id %}
<option selected value="{{ row.id }}">{{ row.title }}</option>
{% else %}
<option value="{{ row.id }}">{{ row.title }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>
- teachet.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.hide{
display: none;
}
.shadow{
/*相对于窗口*/
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
opacity: 0.4;
z-index: 999;
}
.loading{
position: fixed;
width: 32px;
height: 32px;
left: 50%;
top:50%;
margin-left: -16px;
margin-top: -16px;
background-image: url("/static/images/loading.gif");
}
.add-modal{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 300px;
z-index: 1000;
background-color: white;
margin-left: -200px;
margin-top: -200px;
}
</style>
</head>
<body>
<h1>老师列表</h1>
<a href="/add_teacher/">添加</a>
<a id="btnAdd">对话框添加</a>
<table border="1">
<thead>
<tr>
<th>ID</th>
<th>老师姓名</th>
<th>任教班级</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for row in teacher_list %}
<tr>
<td>{{ row.tid }}</td>
<td>{{ row.name }}</td>
<td>
{% for item in row.titles %}
<span style="display: inline-block;padding: 5px; border: 1px solid red;">{{ item }}</span>
{% endfor %}
</td>
<td>
<a href="/edit_teacher/?nid={{ row.tid }}">编辑</a>
|
<a>删除</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
<div id="shadow" class="shadow hide"></div>
<div id="loading" class="loading hide"></div>
<div id="addModal" class="add-modal hide">
<p>
老师姓名:<input type="text" name="name" id="addName" />
</p>
<p>
<select id="classIds" multiple size="10">
</select>
</p>
<a id="addSubmit">提交</a>
</div>
<script src="/static/jquery-1.12.4.js"></script>
<script>
$(function(){
bindAdd();
bindAddSubmit();
});
function bindAdd(){
$('#btnAdd').click(function(){
$('#shadow,#loading').removeClass('hide');
/*
发送ajax请求,获取所有班级信息
再classIds下拉框中生成option
*/
$.ajax({
url:'/get_all_class/',
type:'GET',
dataType: 'JSON',
success:function(arg){
/*
arg = [
{id:1,title:xx}
{id:1,title:xx}
{id:1,title:xx}
]
*/
//console.log(arg);
// 将所有的数据添加到select,option
$.each(arg,function(i,row){
var tag = document.createElement('option');
tag.innerHTML = row.title;
tag.setAttribute('value',row.id);
$('#classIds').append(tag);
});
$('#loading').addClass('hide');
$('#addModal').removeClass('hide');
}
})
})
}
function bindAddSubmit(){
$('#addSubmit').click(function(){
var name = $('#addName').val();
var class_id_list = $('#classIds').val();
console.log(name,class_id_list);
$.ajax({
url:'/modal_add_teacher/',
type: 'POST',
data: {'name':name, 'class_id_list': class_id_list},
dataType:'JSON',
traditional: true,// 如果提交的数据的值有列表,则需要添加此属性
success: function (arg) {
if(arg.status){
location.reload();
}else{
alert(arg.message);
}
}
})
});
}
</script>
</body>
</html>
- add_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>添加老师</h1>
<form method="POST" action="/add_teacher/">
<p><input type="text" name="name" placeholder="老师姓名" /></p>
<p>
<select multiple size="10" name="class_ids">
{% for item in class_list %}
<option value="{{ item.id }}">{{ item.title }}</option>
{% endfor %}
</select>
</p>
<input type="button" value="提交" />
</form>
</body>
</html>
- edit_teacher.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>编辑老师</h1>
<form method="POST" action="/edit_teacher/?nid={{ teacher_info.id }}">
<p><input type="text" name="name" value="{{ teacher_info.name }}" /></p>
<p>
<select name="class_ids" multiple size="10">
{% for item in class_list %}
{% if item.id in class_id_list %}
<option value="{{ item.id }}" selected>{{ item.title }}</option>
{% else %}
<option value="{{ item.id }}">{{ item.title }}</option>
{% endif %}
{% endfor %}
</select>
</p>
<input type="submit" value="提交" />
</form>
</body>
</html>