<!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: 0px 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.name}}</td>
<td>{{row.age}}</td>
<td>{{row.gender}}</td>
<td>{{row.cs.name}}</td>
<td>
<a href="#" class="glyphicon glyphicon-remove icon del-row"></a>
<a href="#" class="fa fa-pencil-square-o icon"></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">
{# 不能用stu_list循環,要用cls_list循環,否則會出現重複 #}
{% for row in cls_list %}
<option value="{{row.id}}">{{row.name}}</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="modal-content">
<div class="alert alert-danger" role="alert">
<h3>刪除學生信息?</h3>
<div>
<input type="text" id="delNid" style="display: none;">
</div>
<div>
<button type="button" class="btn btn-default">取消</button>
<button type="button" class="btn btn-warning" id="delConfirm">肯定刪除</button>
</div>
</div>
</div>
</div>
</div>
{# jquery必須放插件前 #}
<script src="/static/js/jquery-3.1.1.js"></script>
<script src="/static/plugins/bootstrap/js/bootstrap.js"></script>
<script>
$(function() {
bindEvent();
bindSave();
bindDel();
bindDelConfirm();
});
function bindDel() {
$('#tb').on('click','.del-row',function() {
$('#delModal').modal('show');
//獲取當前行的ID
var rowId = $(this).parent().parent().attr('nid');
//設置給delNid
$('#delNid').val(rowId);
});
}
function bindDelConfirm() {
$('#delConfirm').click(function() {
var nid = $('#delNid').val();
$.ajax({
url: '/del_student.html',
type: 'GET',
data: {nid: nid},
success: function(arg) {
var dict = JSON.parse(arg);
if(dict.static) {
$('tr[nid="'+ nid +'"]').remove();
$('#delModal').modal('hide');
}
}
});
});
}
function bindEvent() {
$('#addBtn').click(function() {
$('#addModal').modal('show');
});
}
function bindSave() {
$('#btnSave').click(function() {
// 獲取表單全部信息,可優化,見最後
var postData = {};
$('#addModal').find('input,select').each(function () {
console.log($(this)[0]);
var v = $(this).val();
var n = $(this).attr('name');
if(name=='gender'){
if($(this).prop('checked')){
postData[n] = v;
}
}else{
postData[n] = v;
}
});
console.log(postData);
$.ajax({
url: '/addStudent.html',
type: 'POST',
data: postData,
success: function(arg) {
console.log(arg);
//arg爲字符串
//JSON.parse將字符串轉行爲字典
var dict = JSON.parse(arg);
//字典用點取值
if(dict.status) {
//window.location.reload();
//自增id = dict.data
createRow(postData, dict.data);
//關閉對話框
$('#addModal').modal('hide');
}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 tdAge = document.createElement('td');
if(postData.gender == '1') {
tdAge.innerHTML = 'True';
}else{
tdAge.innerHTML = 'False';
}
$(tr).append(tdAge);
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 = '<a class="glyphicon glyphicon-remove icon del-row"></a><a class="fa fa-pencil-square-o icon"></a>';
$(tr).append(tdHandle);
$('#tb').append(tr);
}
}
</script>
</body>
</html>
from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.
def students(request):
stu_list = models.Students.objects.all()
cls_list = models.Classes.objects.all()
return render(request,"students.html",{"stu_list": stu_list, 'cls_list': cls_list})
import json
def addStudent(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.Students.objects.create(
name=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):
response = {'static': True, 'message': None}
try:
nid = request.GET.get("nid")
models.Students.objects.filter(id=nid).delete()
except Exception as e:
print(555555555,type(e))
response['static'] = False
result = json.dumps(response)
return HttpResponse(result)
Python:css
字符串 = json.dumps(對象) html
對象 = json.loads(字符串)前端
JavaScript:python
對象 = JSON.parse(字符串)jquery
字符串 = JSON.stringify(對象)ajax
應用場景:django
數據傳輸時,發送和接收都以字符串形式進行json
$.ajax({bootstrap
url: 服務器
type:
data:
dataType: 'JSON', // 自動把arg轉爲對象
success: function(arg) {
// arg是對象
}
})
$('要綁定標籤的上級標籤’).on('click', '要綁定的標籤',function() {} )
$('要綁定標籤的上級標籤’).delegate( '要綁定的標籤','click',function() {} )
/*獲取表單全部信息方式
一、使用each循環
二、var data = $('#form表單的ID').serialize() (優化推薦)
data存爲字典類型,可直接調用
*/
argument list
自變量列表
Internal Server Error
內部服務器錯誤
存在的bug:添加學生後不能直接刪除,要刷新才能作刪除操做