具于django ajax实现增 删 改 查功能
代码示例:
代码:
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'^students/', views.students), url(r'^add_student/', views.add_student), url(r'^del_student/', views.del_student), url(r'^edit_student/', views.edit_student), url(r'^test_ajax_list/', views.test_ajax_list), ]
settings.py
STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR,'static'), )
models.py
from django.db import models from django.db import models class Classes(models.Model): """ 班级表,男 """ title = models.CharField(max_length=32) m = models.ManyToManyField("Teachers") class Teachers(models.Model): """ 老师表,女 """ name = models.CharField (max_length=32) class Student(models.Model): username = models.CharField(max_length=32) age = models.IntegerField() gender = models.BooleanField() cs = models.ForeignKey(Classes)
添加功能:
编辑功能:
views.py
from django.shortcuts import render from django.shortcuts import HttpResponse from app01 import models import json def students(request): cls_list = models.Classes.objects.all() stu_list = models.Student.objects.all() return render(request,'students.html',{'stu_list':stu_list,'cls_list':cls_list}) def add_student(request): response = {'status':True,'message': None,'data':None} try: u = request.POST.get('username') a = request.POST.get('age') g = request.POST.get('gender') c = request.POST.get('cls_id') obj = models.Student.objects.create( username=u, age=a, gender=g, cs_id=c ) response['data'] = obj.id except Exception as e: response['status'] = False response['message'] = '用户输入错误' result = json.dumps(response,ensure_ascii=False) return HttpResponse(result) def del_student(request): ret = {'status': True} try: nid = request.GET.get('nid') models.Student.objects.filter(id=nid).delete() except Exception as e: ret['status'] = False return HttpResponse(json.dumps(ret)) def edit_student(request): response = {'code':1000, 'message': None} try: nid = request.POST.get('nid') user = request.POST.get('user') age = request.POST.get('age') gender = request.POST.get('gender') cls_id = request.POST.get('cls_id') models.Student.objects.filter(id=nid).update( username=user, age=age, gender=gender, cs_id=cls_id ) except Exception as e: response['code'] = 1001 response['message'] = str(e) return HttpResponse(json.dumps(response)) def test_ajax_list(request): print(request.POST.getlist('k')) return HttpResponse('...')
students.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <link rel="stylesheet" href="/static/plugins/bootstrap/css/bootstrap.css"/> <link rel="stylesheet" href="/static/plugins/font-awesome/css/font-awesome.css"/> <style> .icon { margin: 0 5px; } </style> </head> <body> <div class="container"> <div style="padding: 20px 0;"> <a class="btn btn-primary" id="addBtn">添加</a> <a class="btn btn-danger">删除</a> </div> <div> <table class="table table-bordered table-striped"> <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 }}"> <td na="nid">{{ row.id }}</td> <td na="user">{{ row.username }}</td> <td na="age">{{ row.age }}</td> <td na="gender">{{ row.gender }}</td> <td na="cls_id" cid="{{ row.cs_id }}">{{ row.cs.title }}</td> <td> <a class="glyphicon glyphicon-remove icon del-row"></a><a class="fa fa-pencil-square-o icon edit-row"></a> </td> </tr> {% endfor %} </tbody> </table> </div> </div> <!-- Modal --> <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 id="fm" 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" 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="cls_id"> {% for row in cls_list %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> </div> </div> </form> </div> <div class="modal-footer"> <span id="errorMsg" style="color: red;"></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> <!-- Modal --> <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>...<input style="display: none;" type="text" id="delNid" /></div> <div> <button type="button" class="btn btn-default">取消</button> <button id="delConfirm" type="button" class="btn btn-danger">确定</button> </div> </div> </div> </div> <!-- Modal --> <div class="modal fade" id="eidtModal" 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 id="fm" 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" 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="cls_id"> {% for row in cls_list %} <option value="{{ row.id }}">{{ row.title }}</option> {% endfor %} </select> </div> </div> </form> </div> <div class="modal-footer"> <span id="errorMsg" style="color: red;"></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(); bindEdit(); bindEditConfirm(); }); /* 编辑提交事件 */ function bindEditConfirm() { $('#btnEditSave').click(function () { var postData = {}; $('#eidtModal').find('input,select').each(function () { 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/', type: 'POST', data: postData, dataType: 'JSON', success:function (arg) { if(arg.code == 1000){ window.location.reload(); }else{ alert(arg.message); } } }) }) } /* 绑定编辑按钮点击事件 */ function bindEdit() { $('#tb').on('click','.edit-row',function () { $('#eidtModal').modal('show'); //1.获取当前行的所有数据 // 将数据赋值到对应的对话框的指定位置 $(this).parent().prevAll().each(function () { // cls_id var v = $(this).text(); var n = $(this).attr('na'); if(n=='cls_id'){ var cid = $(this).attr('cid'); $('#eidtModal select[name="cls_id"]').val(cid); }else if(n=='gender'){ // v=True if(v=='True'){ $('#eidtModal :radio[value="1"]').prop('checked',true); }else{ $('#eidtModal :radio[value="0"]').prop('checked',true); } }else { // n=age // v=12 $("#eidtModal input[name='"+ n +"']").val(v) } }); }) } function bindDelConfirm() { $('#delConfirm').click(function () { var rowId = $('#delNid').val(); console.log(rowId); $.ajax({ url: '/del_student/', 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 () { $('#delModal').modal('show'); // 回去当前行的ID var rowId = $(this).parent().parent().attr('nid'); $('#delNid').val(rowId); }) } function bindEvent() { $('#addBtn').click(function () { $('#addModal').modal('show'); }) } function bindSave() { $('#btnSave').click(function () { var postData = {}; $('#addModal').find('input,select').each(function () { var v = $(this).val(); var n = $(this).attr('name'); if(n=='gender'){ if($(this).prop('checked')){ postData[n] = v; } }else{ postData[n] = v; } }); /* postData = { username: 'asdf', age:18, gender: 1, cls_id: 2 } */ $.ajax({ url: '/add_student/', type: 'POST', data: postData, success:function (arg) { // arg是字符串 // JSON.parse将字符串转换成字典, json.loads var dict = JSON.parse(arg); if(dict.status){ /* postData = { username: 'asdf', age:18, gender: 1, cls_id: 2 } 自增id = dict.data */ createRow(postData,dict.data); $('#addModal').modal('hide'); // window.location.reload(); }else { $('#errorMsg').text(dict.message); } } }) }); } function createRow(postData,nid) { var tr = document.createElement('tr'); $(tr).attr('nid',nid); var tdId = document.createElement('td'); tdId.innerHTML = nid; $(tr).append(tdId); var tdUser = document.createElement('td'); tdUser.innerHTML = postData.username; $(tr).append(tdUser); var tdAge = document.createElement('td'); tdAge.innerHTML = postData.age; $(tr).append(tdAge); var tdGender = document.createElement('td'); if(postData.gender == "0"){ tdGender.innerHTML = 'False'; }else{ tdGender.innerHTML = 'True'; } $(tr).append(tdGender); var tdClass = document.createElement('td'); var text = $('select[name="cls_id"]').find('option[value="'+ postData.cls_id +'"]').text(); tdClass.innerHTML = text; $(tr).append(tdClass); var tdHandle = '<td> <a class="glyphicon glyphicon-remove icon del-row"></a><a class="fa fa-pencil-square-o icon edit-row"></a> </td>'; $(tr).append(tdHandle); $('#tb').append(tr); } </script> </body> </html>