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': ''},
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">×</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">×</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">×</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>
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的更多相关文章
- python 全栈开发,Day75(Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件)
昨日内容回顾 基于对象的跨表查询 正向查询:关联属性在A表中,所以A对象找关联B表数据,正向查询 反向查询:关联属性在A表中,所以B对象找A对象,反向查询 一对多: 按字段:xx book ----- ...
- Django与Ajax,文件上传,ajax发送json数据,基于Ajax的文件上传,SweetAlert插件
一.Django与Ajax AJAX准备知识:JSON 什么是 JSON ? JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation) JSON 是轻 ...
- python Django之Ajax
python Django之Ajax AJAX,Asynchronous JavaScript and XML (异步的JavaScript和XML),一种创建交互式网页应用的网页开发技术方案. 异步 ...
- django 接受 ajax 传来的数组对象
django 接受 ajax 传来的数组对象 发送:ajax 通过 POST 方式传来一个数组 接收:django 接受方式 array = request.POST.getlist(‘key[]’) ...
- Django使用AJAX调用自己写的API接口
Django使用AJAX调用自己写的API接口 *** 具体代码和数据已上传到github https://github.com/PythonerKK/eleme-api-by-django-rest ...
- Bootstrap + Font Awesome
将Font Awesome 集成到 Bootstrap 非常容易,还可以被单独使用. 最简单的 Bootstrap + Font Awesome 集成方式 使用这种方式将 Font Awesome 集 ...
- Django之Ajax提交
Ajax 提交数据,页面不刷新 Ajax要引入jQuery Django之Ajax提交 Js实现页面的跳转: location.href = "/url/" $ajax({ url ...
- Django框架第九篇--Django和Ajax、序列化组件(serializers)、自定义分页器、模型表choice参数
Django和Ajax 一.什么是Ajax AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步的Javascript和XML”.即使用Javascript语 ...
- Django之AJAX传输JSON数据
目录 Django之AJAX传输JSON数据 AJAX 中 JSON 数据传输: django响应JSON类型数据: django 响应 JSON 类型数据: Django之AJAX传输JSON数据 ...
- Django之ajax(jquery)封装(包含 将 csrftoken 写入请求头方法)
由于支持问题,未使用 es6 语法 _ajax.js /** * 发起请求 * @param url 请求地址 * @param data 请求数据 { } json格式 * @param type ...
随机推荐
- jQuery-mobilevalidate使用 的一些心得,小小总结
在做M站时比较纠结的是表单验证,不像pc端,移动端的验证要求插件更小更轻量,更加灵活,说不定是冒气泡的报错提示?! 介绍一款好用的移动端的表单验证插件:jQuery-mobilevalidate: 代 ...
- npm install、npm install --save、npm install --save --dev、npm install -S、npm install -D的区别
npm install X: 会把X包安装到node_modules目录中 不会修改package.json 之后运行npm install命令时,不会自动安装X npm install X –sav ...
- spring boot session error
Error starting ApplicationContext. To display the conditions report re-run your application with 'de ...
- final关键字的用法
final关键字的作用 1.被final修饰的类不能被继承 报错信息:cannot inherit from final 'com.dajia.test.Animal' 2.被final修饰的方法不能 ...
- 前端框架framework和库library的一点区别和记录
本篇纯文字,无关代码,只是一点概念的记录 关于所谓前端 首先学的是HTML5.CSS3.JavaScript这三个 之后接触了一下UI框架,如layui和bootstrap 目前是打算去学VUE和an ...
- Android SDK Tools 24.3.2 Build脚本Bug
如下图版本: 在%Android_home%\tools\ant\build.xml中, 在483行附近, 少了aidl,aapt,dx, zipalign四个变量的声明. 加上就OK了. <p ...
- 三种bean创建方式
- controller层负责创建类传递类给service;service层负责逻辑编写调用dao层 将编写后的类传递到dao层,保证事务的正确性;dao层负责数据的持久化
controller层负责创建类传递类给service:service层负责逻辑编写调用dao层 将编写后的类传递到dao层,保证事务的正确性:dao层负责数据的持久化
- UVA 11988 Beiju Text
https://vjudge.net/problem/UVA-11988 题目 你有一个破损的键盘.键盘上所有的键都可以正常工作,但有时候Home键或者End键会自动按下.你并不知道键盘存在这一问题, ...
- 安装使用nginx
nginx的优势 是c语言开发的一个web框架 官方声称支持10W+的并发 天下武功 唯快不破 tengine+ uwsgi(多进程) + django 你公司的技术栈是什么样? centos7 + ...