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. 手机端图像编辑上传-cropper

    编辑头像,实现相册,照像功能,并能缩放裁剪功能,可自定义UI,引用'cropper.js', 'exif.js' /*初始化裁剪插件*/ var screenWidth = $(window).wid ...

  2. 不停机修改线上 MySQL 主键字段 以及其带来的问题和总结思考

    起因: 线上 user 数据库没有自增字段,数据量已经达到百万级.无论是给离线仓库还是数据分析同步数据,没有主键自增 id 都是杀手级的困难.所以在使用 create_time 痛苦了几次之后准备彻底 ...

  3. QTP 自动化测试桌面程序--笔记(下拉选择、右键菜单、在控件仓库中查找对应的控件)

    0 在收集窗口控件信息时-最好将可输入的文字去掉,不然控件的名称按输入的文字标记 1 编辑时录制脚本-默认按当前显示的填入的数据标记控件 可以使用 tool-spy-查看控件的x,y 坐标,按坐标在学 ...

  4. flask 保存文件到 七牛云

    上篇文章队长讲述了如何把前端上传的文件保存到本地项目目录 本篇 讲述一下把前端上传的文件保存到 第三方存储(七牛云) 七牛云相关步骤思路: 首先 进去七牛云官网,注册并实名认证来获取一个七牛云账号和存 ...

  5. Tyche 2147 旅行

    题目描述 你有m元钱,将要游览n个国家.每一个国家有一种商品,其中第i个国家商品的单价为ai元.每到一个国家,你会用手上的钱疯狂购买这个国家的商品,直到剩余的钱无法购买为止. 现在你要决定游览这n个国 ...

  6. Civil 3D 二次开发 创建Civil 3D 对象—— 01 —— 创建几何空间点

    这一小节,我们创建派生于CivilCreateEntityDemo的类CivilCreateCogoPoint,来创建几何空间点. 1 创建类并添加字段及方法 首先在项目资源管理器中向本项目中添加类, ...

  7. BZOJ1324Exca王者之剑&BZOJ1475方格取数——二分图最大独立集

    题目描述   输入 第一行给出数字N,M代表行列数.N,M均小于等于100 下面N行M列用于描述数字矩阵 输出 输出最多可以拿到多少块宝石 样例输入 2 2 1 2 2 1 样例输出 4   题意就是 ...

  8. SpringMVC 集成Log4j

    项目地址:https://github.com/xiaoqiu-duan/DataProject.git 1.添加jar <dependency> <groupId>org.s ...

  9. Python中操作ini配置文件

    这篇博客我主要想总结一下python中的ini文件的使用,最近在写python操作mysql数据库,那么作为测试人员测试的环境包括(测试环境,UAT环境,生产环境)每次需要连接数据库的ip,端口,都会 ...

  10. JS 实现DIV 滚动至顶部后固定

    JS 实现DIV 滚动至顶部后固定 <!DOCTYPE HTML> <html> <head> <meta charset="UTF-8" ...