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. 集合之ArrayList(含JDK1.8源码分析)

    一.ArrayList的数据结构 ArrayList底层的数据结构就是数组,数组元素类型为Object类型,即可以存放所有类型数据.我们对ArrayList类的实例的所有的操作(增删改查等),其底层都 ...

  2. Python2.7从入门到精通

    快速入门 1.程序输出print语句 (1)使用print语句可查看对象的值:在交互式解释器使用对象本身则输出此对象的字符串表示: (2)使用print语句调用str()显示对象:在交互式解释器使用对 ...

  3. Vue-router的API详解

    前面的话 本文将详细介绍Vue-router的API router-link <router-link> 组件支持用户在具有路由功能的应用中点击导航. 通过 to 属性指定目标地址,默认渲 ...

  4. endnote插入文献时出现{,#}这样的乱码

    1)在每次插入文献后,再点击一下Bibliography里面的Update Citation and Bibliography即可: (2)较好的解决方法也较为简单,只需要再一次进入Word中的End ...

  5. JarvisOJ Misc 炫酷的战队logo

    欣赏过了实验室logo,有人觉得我们战队logo直接盗图比较丑,于是我就重新设计了一个,大家再欣赏下? 一开始拿到的BMP文件就打不开,用010打开发现文件头被抹去了,补上了BMP,与文件大小后,发现 ...

  6. Codeforces 888G(分治+trie)

    按位贪心,以当前考虑位是0还是1将数分成两部分,则MST中这两部分之间只会存在一条边,因为一旦有两条或以上的边,考虑两条边在原图中所成的环,显然这两条边有一条是环上的权值最大边,不会出现在MST中.则 ...

  7. POJ2187-Beauty Contest-凸包

    平面最远点对 由于点数为1e5,而整数点的情况下,凸包上点的个数为sqrt(M),M为范围. 这样求出凸包之后n^2枚举维护距离就可以了 否则就用旋转卡壳. 这里用了挑战上的做法,比较简洁. #inc ...

  8. C# Timer 的区别

    首先,我们看一下 3种Timer 1.System.Threading.Timer 2.System.Timers.Timer 3.System.Windows.Forms.Timer 主要区别,其实 ...

  9. 洛谷P2085最小函数值题解

    题目 首先我们先分析一下题目范围,\(a,b,c\) 都是整数,因此我们可以得出它的函数值在\((0,+\infty )\)上是单调递增的,,然后我们可以根据函数的性质,将每个函数设置一个当前指向位置 ...

  10. Docker基本使用(二)

    Docker 客户端 我们可以直接输入 docker 命令来查看到 Docker 客户端的所有命令选项. 可以通过命令 docker command --help 更深入的了解指定的 Docker 命 ...