prop,attr,val

font-awesome:字体,图标库

对话框添加,删除,修改:
添加:
Ajax偷偷向后台发请求:
1. 下载引入jQuery
2.
$.ajax({
url: '/add_classes.html',
type: 'POST',
data: {'username':'root','password': ''},
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),
]

urls

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)

views

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)

models

<!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">&times;</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=""> 男
</label>
<label class="radio-inline">
<input type="radio" name="gender" value=""> 女
</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>

student.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">&times;</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>

student.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),
]

urls

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))

views

实例三(编辑信息)

<!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">&times;</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">&times;</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>

student.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)

views

"""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),
]

urls

总结:

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
}
});

Django(十三)ajax 与 Bootstrap,font-awesome的更多相关文章

  1. python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)

    昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...

  2. Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件

    一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...

  3. python Django之Ajax

    python Django之Ajax AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案. 异步 ...

  4. django 接受 ajax 传来的数组对象

    django 接受 ajax 传来的数组对象 发送:ajax 通过 POST 方式传来一个数组 接收:django 接受方式 array = request.POST.getlist(‘key[]’) ...

  5. Django使用AJAX调用自己写的API接口

    Django使用AJAX调用自己写的API接口 *** 具体代码和数据已上传到github https://github.com/PythonerKK/eleme-api-by-django-rest ...

  6. Bootstrap + Font Awesome

    将Font Awesome 集成到 Bootstrap 非常容易,还可以被单独使用. 最简单的 Bootstrap + Font Awesome 集成方式 使用这种方式将 Font Awesome 集 ...

  7. Django之Ajax提交

    Ajax 提交数据,页面不刷新 Ajax要引入jQuery Django之Ajax提交 Js实现页面的跳转: location.href = "/url/" $ajax({ url ...

  8. Django框架第九篇--Django和Ajax、序列化组件(serializers)、自定义分页器、模型表choice参数

    Django和Ajax 一.什么是Ajax AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步的Javascript和XML”.即使用Javascript语 ...

  9. Django之AJAX传输JSON数据

    目录 Django之AJAX传输JSON数据 AJAX 中 JSON 数据传输: django响应JSON类型数据: django 响应 JSON 类型数据: Django之AJAX传输JSON数据 ...

  10. Django之ajax(jquery)封装(包含 将 csrftoken 写入请求头方法)

    由于支持问题,未使用 es6 语法 _ajax.js /** * 发起请求 * @param url 请求地址 * @param data 请求数据 { } json格式 * @param type ...

随机推荐

  1. Appscanner实验还原code3

    # Author: Baozi #-*- codeing:utf-8 -*- import _pickle as pickle from sklearn import ensemble import ...

  2. 记一次tomcat7.0版本启动项目失败问题

    测试项目在tomcat7中启动失败,报错如下: @794314bc3 Error during job execution (jobs.Bootstrap) Oops: VerifyError ~ p ...

  3. input & collapse & tags

    input & collapse & tags https://ant.design/components/tag-cn/ https://www.iviewui.com/compon ...

  4. tomcat 和jboss区别

    参考http://blog.csdn.net/sz_bdqn/article/details/6762175

  5. Nginx 网络事件

    L27-29 应用层(如浏览器等一系列组成的发送get请求) 传输层 系统内核打开一个端口将客户端IP及端口和服务端IP及端口记录下来一并传输到网络层 网络层 打包后到链路层 再到客户端路由器至广域网

  6. Nginx split_client模块

    一般用户AB测试根据比例调用指定的接口  默认编译进nginx Syntax: split_clients string $variable { ... } Default: — Context: h ...

  7. 【C/C++】实现龙贝格算法

    1. 复化梯形法公式以及递推化 复化梯形法是一种有效改善求积公式精度的方法.将[a,b]区间n等分,步长h = (b-a)/n,分点xk = a + kh.复化求积公式就是将这n等分的每一个小区间进行 ...

  8. 我踩过的Alwayson的坑!

    最近被sql server Alwayson高可用组和读写分离,弄得神魂颠倒,身心俱疲.遇到了下面一些问题,提醒自己也给后来人做些记录. EntityFramework支不支持Alwayson? 起因 ...

  9. 查询SQLSERVER中系统所有表

    SQL 查询所有表名: SELECT NAME FROM SYSOBJECTS WHERE TYPE='U' SELECT * FROM INFORMATION_SCHEMA.TABLES 查询表的所 ...

  10. RMQ--ST表

    RMQ即区间最值查询,是指这样一个问题:对于长度为n的数列A,回答若干询问RMQ(A,i,j)(i,j<=n),返回数列A中下标在i,j之间的最小/大值. ST表既ST算法是一个非常有名的在线处 ...