Django(十三)ajax 与 Bootstrap,font-awesome
prop,attr,val
font-awesome:字体,图标库
对话框添加,删除,修改: 添加: Ajax偷偷向后台发请求: 1. 下载引入jQuery 2. $.ajax({ url: '/add_classes.html', type: 'POST', data: {'username':'root','password': '123'}, success:function(arg){ // 回调函数,arg是服务端返回的数据 } })
实例一(创建信息):
"""ajax_learn URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('students/', views.students), path('add_student/', views.add_student), ]
from django.shortcuts import render,HttpResponse from app01 import models # Create your views here. def students(request): student_list = models.Student.objects.all() class_list = models.Classes.objects.all() return render(request, "students.html", {"student_list": student_list, "class_list": class_list}) def add_student(request): response = {'status': True, 'message': None} print(request.POST) ''' <QueryDict: {'username': ['Mike'], 'age': ['29'], 'gender': ['1'], 'class_id': ['3']}> ''' try: u = request.POST.get("username") a = request.POST.get("age") g = request.POST.get("gender") c = request.POST.get("class_id") models.Student.objects.create(username=u, age=a, gender=g, cs_id=c) except Exception as e: response['status'] = False response['message'] = '用户输入错误' import json result = json.dumps(response, ensure_ascii=False) return HttpResponse(result)
from django.db import models # Create your models here. 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(null=True) cs = models.ForeignKey(Classes, on_delete=models.CASCADE)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>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> .icon { margin: 0px 5px; } </style> </head> <body> <div class="container"> <div style="padding: 20px 0"> <a href="#" class="btn btn-primary" id="addBtn">添加</a> <a href="#" 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> {% for row in student_list %} <tr> <td>{{ row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.age }}</td> <td>{{ row.gender }}</td> <td>{{ row.cs.title }}</td> <td> <a href="#" class="glyphicon glyphicon-remove icon"></a> <a href="#" class="fa fa-pencil-square-o icon" style="font-size: 17px"></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 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="gender" 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="classes" class="col-sm-2 control-label">班级</label> <div class="col-sm-10"> <select class="form-control" name="class_id"> {% for row in class_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> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script> <script> $(function () { bindEvent(); bindSave(); }); function bindEvent() { $("#addBtn").click(function () { $("#addModal").modal('show'); }) }; function bindSave() { $("#btnSave").click(function () { var postData = {}; $(".modal").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/", type:"POST", data:postData, success:function (arg) { // arg是字符串 // JSON.parse将字符串转换成字典, json.loads var dict = JSON.parse(arg); if(dict.status){ window.location.reload(); }else { $("#errorMsg").text(dict.message); } } }) }); } </script> </body> </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>{{ row.id }}</td> <td>{{ row.username }}</td> <td>{{ row.age }}</td> <td>{{ row.gender }}</td> <td>{{ row.cs.title }}</td> <td> <a class="glyphicon glyphicon-remove icon del-row"></a> <a class="fa fa-pencil-square-o icon" style="font-size: 17px"></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 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> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/plugins/bootstrap/js/bootstrap.js"></script> <script> $(function () { bindEvent(); bindSave(); delEvent(); delConfirm(); }); function delConfirm() { $("#delConfirm").click(function () { var row_id = $('#delNid').val(); console.log(row_id); $.ajax({ url:"/del_student/", type:"GET", data:{"nid":row_id}, success:function (arg) { console.log(arg); var dic = JSON.parse(arg); console.log(dic); if(dic.status) { $('tr[nid="'+ row_id+'"]').remove(); } $("#delModal").modal('hide'); } }) }) } function delEvent() { $(".del-row").click(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; } }); $.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); {#window.location.reload();#} }else { $('#errorMsg').text(dict.message); } } }) $(".modal").modal('hide') }); } function createRow(postData, nid) { var tr = document.createElement('tr'); var td_id = document.createElement('td'); td_id.innerHTML = nid; tr.appendChild(td_id); var td_name = document.createElement('td'); td_name.innerHTML = postData.username; tr.appendChild(td_name) var td_age = document.createElement('td'); td_age.innerText = postData.age; tr.appendChild(td_age); var td_gender = document.createElement('td'); if (postData.gender == "1") { td_gender.innerHTML = 'True'; }else { td_gender.innerHTML = "False"; } tr.appendChild(td_gender); var td_class = document.createElement('td'); var text = $("select[name='cls_id']").find("option[value='"+postData.cls_id+"']").text(); td_class.innerHTML = text; tr.appendChild(td_class); var tdHandle = '<td> <a class="glyphicon glyphicon-remove icon"></a><a class="fa fa-pencil-square-o icon" style="font-size: 17px"></a> </td>'; $(tr).append(tdHandle); $("#tb").append(tr) } </script> </body> </html>
"""django_ajax URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('students/', views.students),
path('add_student/', views.add_student),
path('del_student/', views.del_student),
]
from django.shortcuts import render,HttpResponse # Create your views here. 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))
实例三(编辑信息)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>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> .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="username">{{ 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="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 id="fm" class="form-horizontal edit-form"> <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="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> <script src="/static/js/jquery-3.3.1.js"></script> <script src="/static/plugins/bootstrap-3.3.7-dist/js/bootstrap.js"></script> <script> $(function () { bindEvent(); bindSave(); bindDel(); bindDelConfirm(); bindEdit(); bindEditConfirm(); }); function bindEditConfirm() { $("#editModal #btnSave").click(function () { var data = $(".edit-form").serialize(); console.log(data); $.ajax({ url:"/edit_student/", type:"POST", data:data, dataType:'JSON', success:function (arg) { if(arg.status){ window.location.reload(); }else{ alert(arg.message); } } }) }) } function bindEdit() { $("#tb").on('click','.edit-row',function () { $("#editModal").modal('show'); var tds = $(this).parent().prevAll().text(); console.log(tds); var values_list= []; $(this).parent().prevAll().each(function () { var v = $(this).text(); var n = $(this).attr('na'); if (n=="gender") { if (v=="True") { $("#editModal input[value='1']").prop("checked",true); } else if (v=="False") { $("#editModal input[value='0']").prop("checked", true); } } else if(n=="cls_id") { var cid = $(this).attr('cid'); $("#editModal select[name='cls_id']").val(cid); console.log(cid) } else { $("#editModal input[name='"+n+"']").val(v); } values_list.push(n) }); console.log(values_list) }); } function bindDelConfirm() { $('#delConfirm').click(function () { var rowId = $('#delNid').val(); console.log(rowId); $.ajax({ url: '/del_student/', type: 'GET', data: {'nid': rowId}, dataType:'JSON', success:function (arg) { /*var dict = JSON.parse(arg);*/ console.log(arg); if(arg.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'); console.log(rowId); $('#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>
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')
print(nid)
models.Student.objects.filter(id=nid).delete()
except Exception as e:
ret['status'] = False
print(e)
return HttpResponse(json.dumps(ret))
def edit_student(request):
response = {'status':True,'message': None,'data':None}
try:
nid = request.POST.get('nid')
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.filter(id=nid).update(
username=u,
age=a,
gender=g,
cs_id=c
)
# response['data'] = obj.id
except Exception as e:
response['status'] = False
response['message'] = e
result = json.dumps(response,ensure_ascii=False)
return HttpResponse(result)
"""ajax_learn URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from app01 import views urlpatterns = [ path('admin/', admin.site.urls), path('students/', views.students), path('add_student/', views.add_student), path('del_student/',views.del_student), path('edit_student/',views.edit_student), ]
总结:
1.
Python序列化
字符串 = json.dumps(对象) 对象->字符串
对象 = json.loads(字符串) 字符串->对象
JavaScript:
字符串 = JSON.stringify(对象) 对象->字符串
对象 = JSON.parse(字符串) 字符串->对象
应用场景:
数据传输时,
发送:字符串
接收:字符串 -> 对象
2. ajax
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
success:function(arg){
// arg是字符串类型
// var obj = JSON.parse(arg)
}
})
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':[1,2,3,4]},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
发送数据时:
data中的v
a. 只是字符串或数字
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':'v1'},
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
b. 包含属组
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1':[1,2,3,4]},
dataType: 'JSON',
traditional: true,
success:function(arg){
// arg是对象
}
})
c. 传字典
b. 包含属组
$.ajax({
url: 'http//www.baidu.com',
type: 'GET',
data: {'k1': JSON.stringify({}) },
dataType: 'JSON',
success:function(arg){
// arg是对象
}
})
3. 事件委托
$('要绑定标签的上级标签').on('click','要绑定的标签',function(){})
$('要绑定标签的上级标签').delegate('要绑定的标签','click',function(){})
4. 编辑
5. 总结
新URL方式:
- 独立的页面
- 数据量大或条目多
对话框方式:
- 数据量小或条目少
-增加,编辑
- Ajax: 考虑,当前页;td中自定义属性
- 页面(***)
删除:
对话框
jQuery ajax()使用serialize()提交form数据
- 对话框
- var data = $('#fmForm表单的ID').serialize();
$.ajax({
data: $('#fm').serialize()
})
<form action=""> First name: <input type="text" name="FirstName" value="Bill" /><br /> Last name: <input type="text" name="LastName" value="Gates" /><br /> </form>
$(document).ready(function(){ console.log($("form").serialize()); // FirstName=Bill&LastName=Gates });
这样,我们就可以把序列化的值传给ajax()作为url的参数,轻松使用ajax()提交form表单了,而不需要一个一个获取表单中的值然后传给ajax(),
使用$.post()、$.get()和$.getJSON()也是一样的:
$.post('your url', $("form").serialize(), function(data) {
// your code
}
});
$.get('your url', $("form").serialize(), function(data) {
// your code
}
});
$.getJSON('your url', $("form").serialize(), function(data) {
// your code
}
});