目錄
一、效果展示
二、目標
三、技術選型
四、前端關鍵代碼
2、使用$("selector").load(url) 實作在父頁面內加載子頁面
3、添加用戶
1)頁面布局 - 使用 Bootstrap 的 grid
2)Ajax與服務器資料對接
3)模態框 modal 提示
4、賬號串列使用 DataTables 實作
1)使用ajax從服務器獲取資料
2)多語言設定 oLanguage
3)對資料進行渲染,自定義列 columnDefs
5、洗掉用戶模塊
1)ajax 跟服務器對接資料
6、編輯用戶
1)編輯用戶頁面的資料初始化
2)ajax發起http請求,修改用戶資料
五、后端Flask代碼
1、flask 開啟http服務
2、db資料庫操作
六、啟動命令
附錄:參考資料
一、效果展示



二、目標
實作管理系統模塊 - 賬號管理的增刪改查功能,
三、技術選型
樣式:Bootstrap
前端:jQuery + DataTables
后端:Python Flask
四、前端關鍵代碼
1、左側選單導航nav樣式,詳細說明參考我的文章
【2】案例:Bootstrap 開發 - navs 左側選單,使用iframe 嵌入*.html實作動態切換頁面_YYDataV的博客-CSDN博客
2、使用$("selector").load(url) 實作在父頁面內加載子頁面
<body>
<!-- nav 左側選單欄 -->
<!-- 主布局div -->
<div id="main" class="container"></div>
</main>
<script>
$(document).ready(function () {
$("#main").load('/static/userList.html');
})
</script>
</body>
3、添加用戶
1)頁面布局 - 使用 Bootstrap 的 grid
<!-- 添加賬號 -->
<div id="main" class="container">
<div class="row">
<div class="col-2">
<label for="account">
賬號
</label>
</div>
<div class="col-5">
<input id="account" class="form-control" />
</div>
</div>
<br>
<div class="row">
<div class="col-2">
<label for="password">
密碼
</label>
</div>
<div class="col-5">
<input id="passwd" type="password" class="form-control" />
</div>
</div>
<br>
<div class="row">
<div class="col-2">
<label for="alias">
昵稱
</label>
</div>
<div class="col-5">
<input id="alias" class="form-control" />
</div>
</div>
<br>
<div class="row">
<div class="col-2">
<label for="role">角色</label>
</div>
<div class="col-5">
<label for="roleAdmin">管理員 </label>
<input id="roleAdmin" type="radio" class="form-check-input">
<label for="roleUser">用戶 </label>
<input id="roleUser" type="radio" class="form-check-input">
</div>
</div>
<br>
<div class="row">
<div class="col-2">
</div>
<div class="col-5">
<button id="userAdd" class="btn btn-primary">
添加
</button>
<button id="userEdit" class="btn btn-primary">
編輯
</button>
<a href="/static/userList.html">
<button id="cancel" class="btn btn-primary">
取消
</button>
</a>
</div>
</div>
2)Ajax與服務器資料對接
// 3.新建用戶
$("#userAdd").click(function () {
$("#userAdd").attr("disabled", true);
role = 0;
if ($("#roleAdmin").prop("checked")) {
role = 1;
}
if ($("#roleUser").prop("checked")) {
role = 2;
}
if (0 == role) {
// 錯誤提示
}
$.post(
"/userAdd",
JSON.stringify({
'account': $("#account").val(),
'passwd': $("#passwd").val(),
'alias': $("#alias").val(),
'role': role,
'time': Date.parse(new Date()) / 1000,
}),
function (rsp) {
data = JSON.parse(rsp)
$("#userAdd").attr("disabled", false);
// 更新提示內容
txt = "添加賬號成功!";
if (data.ret) {
txt = "添加賬號失敗!";
}
$("#modal-body").text(txt);
//加載模態框,不要使用 $('#myModal').modal(); -- Bootstrap jquey庫的版本不一致導致的不報錯,不顯示,shit
$('#myModal').modal('show');
}
);
});
3)模態框 modal 提示
modal 模態框HTML定義
<!-- 洗掉事件的 模態框 -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- 模態框頭部 -->
<div class="modal-header">
<h4 class="modal-title">資訊</h4>
<button type="button" class="btn-close" data-bs-dismiss="modal"></button>
</div>
<!-- 模態框內容 -->
<div class="modal-body" id="modal-body">
操作結果
</div>
<!-- 模態框底部 -->
<div class="modal-footer">
<a href="/static/userList.html"><button type="button" class="btn btn-primary"
data-bs-dismiss="modal">確定</button></a>
</div>
</div>
</div>
</div>
modal 模態框 觸發顯示
有的版本使用 $('selector').modal('') 觸發模態框;
有的版本使用 $('selector').modal('show') 觸發模態框,
4、賬號串列使用 DataTables 實作
DataTables :DataTables | Table plug-in for jQuery
1)使用ajax從服務器獲取資料
回應的資料為json型別陣列,需要在dataSrc中指定json資料中的欄位,如本例中為‘data’,
DataTables HTML定義:
<!-- 用戶串列 -->
<table id="userList" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>賬號</th>
<th>角色</th>
<th>昵稱</th>
<th>日期</th>
<th>操作</th>
</tr>
</thead>
<tfoot>
<tr>
<th>ID</th>
<th>賬號</th>
<th>角色</th>
<th>昵稱</th>
<th>日期</th>
<th>操作</th>
</tr>
</tfoot>
</table>
DataTables JS 處理:
$(document).ready(function () {
// 1. 用戶串列初始化
$('#userList').DataTable({
"ajax": {
"url": '/userList',
"type": "POST",
"dataSrc": 'data',
},
// 多語言配置
"oLanguage": {
"sProcessing": "正在加載中......",
"sLengthMenu": "", //"每頁顯示_MENU_條記錄"
"sZeroRecords": "", //"對不起,查詢不到相關資料!"
"sEmptyTable": "無資料!",
"sInfo": "當前顯示_START_到_END_條,共_TOTAL_條記錄",
"sInfoFiltered": "資料表中共為 _MAX_ 條記錄",
"sSearch": "搜索 ",
"oPaginate": {
"sFirst": "首頁",
"sPrevious": "上一頁",
"sNext": "下一頁",
"sLast": "末頁"
},
// 資料加載中,顯示的內容
"sLoadingRecords": "加載中... ",
"sInfoEmpty": "當前顯示 0 到 0, 共 0 條記錄",
},
// 自定義列
"columnDefs": [
{
// 角色 targets 下標從0開始
"targets": 2,
"data": function (row, type, val, meta) {
if (1 == row[2]) {
return "管理員";
}
else if (2 == row[2]) {
return "用戶";
}
return "未知";
}
},
{
// 時間
"targets": 4,
"data": function (row, type, val, meta) {
return formatTimeStamp(row[4]);
}
},
{
// 操作 id
"targets": 5,
orderable: false,
"data": function (row, type, val, meta) {
// 呼叫url
urlEdit = '/static/userOpt.html?id=' + row[0];
// 呼叫函式
urlDel = 'userDel(' + row[0] + ')';
buttonUserEdit = '<a href="' + urlEdit + '"><button type="button" class="btn btn-primary">編輯</button></a> '
buttonUserDel = '<a href="" onclick="' + urlDel + '"><button type="button" class="btn btn-primary">洗掉</button></a> '
return buttonUserEdit + buttonUserDel
},
// "defaultContent": "<button id='userEdit' class='btn btn-primary' type='button'>編輯</button> <button id='userDel' class='btn btn-primary' type='button' >洗掉</button>"
}
],
});
}
});
2)多語言設定 oLanguage
默認為英文,使用oLanguage中的配置項將其定義為中文,
3)對資料進行渲染,自定義列 columnDefs
targets 表示對應列下標(從0開始),data 進行資料渲染函式,
本例中,需要配置【編輯】【洗掉】按鈕,并將用戶ID與其對應,
通過超鏈接<a> href 實作編輯,跳轉到編輯頁面;
通過超鏈接<a> onclick實作洗掉,洗掉結果直接以模態框方式彈出,
5、洗掉用戶模塊
1)ajax 跟服務器對接資料
// 2. 洗掉賬號
function userDel(id) {
$.post(
"/userDel",
JSON.stringify({
'id': id
}),
function (rsp) {
result = JSON.parse(rsp)
txt = "洗掉賬號失敗!";
// 更新提示內容
if (0 == result.ret) {
txt = "洗掉賬號成功!";
}
$("#modal-body").text(txt);
$('#myModal').modal('show');
},
)
};
6、編輯用戶
1)編輯用戶頁面的資料初始化
通過全域變數gUserId,從用戶串列頁面將賬號ID傳遞到編輯頁面,
通過href傳遞id:
"data": function (row, type, val, meta) {
// 呼叫url
urlEdit = '/static/userOpt.html?id=' + row[0];
urlDel = 'userDel(' + row[0] + ')';
// 呼叫函式
buttonUserEdit = '<a href="' + urlEdit + '"><button type="button" class="btn btn-primary">編輯</button></a> '
buttonUserDel = '<a href="" onclick="' + urlDel + '"><button type="button" class="btn btn-primary">洗掉</button></a> '
return buttonUserEdit + buttonUserDel
},
通過getQueryString獲取id,并賦值為gUserId :
// 監聽事件:on
$('#userList').on('draw.dt', function () {
$("a").click(function (e) {
// 編輯用戶,通過全域變數傳遞 gUserId
url = $(this).attr("href")
gUserId = getQueryString(url, "id");
e.preventDefault();
$("#main").load(url);
});
});
使用gUserId從服務器獲取該賬號的其他屬性:
// 1.編輯用戶 - 頁面初始化賦值
if (gUserId) {
$.post(
"/getUserById",
JSON.stringify({
'id': gUserId
}),
function (rsp) {
result = JSON.parse(rsp)
// 更新提示內容
if (0 == result.ret) {
data = result.data;
$("#account").val(data[1]);
$("#passwd").val(data[2]);
if (data[3] == 1) {
$("#roleAdmin").prop("checked", true);
} else {
$("#roleUser").prop("checked", true);
}
$("#alias").val(data[4])
}
}
)
}
2)ajax發起http請求,修改用戶資料
// 2. 編輯用戶
$("#userEdit").click(function () {
role = 0;
if ($("#roleAdmin").prop("checked")) {
role = 1;
}
if ($("#roleUser").prop("checked")) {
role = 2;
}
if (0 == role) {
// 錯誤提示
}
$.post(
"/userEdit",
JSON.stringify({
'id': gUserId,
'account': $("#account").val(),
'passwd': $("#passwd").val(),
'alias': $("#alias").val(),
'role': role
}),
function (rsp) {
data = JSON.parse(rsp)
// 更新提示內容
if (0 == data.ret) {
$("#modal-body").text("編輯賬號成功!");
}
else {
$("#modal-body").text("編輯賬號失敗!");
}
//加載模態框,不要使用 $('#myModal').modal(); -- Bootstrap jquey庫的版本不一致導致的不報錯,不顯示,shit
$('#myModal').modal('show');
}
);
});
五、后端Flask代碼
1、flask 開啟http服務
# -*- coding: utf-8 -*-
from flask import Flask, request
import db
import json
from retCode import *
app = Flask(__name__)
app.debug = True
@app.route('/getUserById', methods=['POST'])
def getUserById():
req = json.loads(request.get_data())
rsp = db.getUserById(req["id"])
result = {
"ret": EOK,
"data": rsp
}
return json.dumps(result)
@app.route('/userList', methods=['POST'])
def userList():
rsp = db.userList()
result = {
"ret": EOK,
"data": rsp
}
return json.dumps(result)
@app.route('/userAdd', methods=['POST'])
def userAdd():
req = json.loads(request.get_data())
db.userAdd(req)
result = {
"ret": EOK
}
return json.dumps(result)
@app.route('/userEdit', methods=['POST'])
def userEdit():
req = json.loads(request.get_data())
db.userEdit(req)
result = {
"ret": EOK
}
return json.dumps(result)
@app.route('/userDel', methods=['POST'])
def userDel():
req = json.loads(request.get_data())
db.userDel(req["id"])
result = {
"ret": EOK
}
return json.dumps(result)
@app.route('/login', methods=['POST'])
def login():
data = json.loads(request.get_data())
account = data.get("account")
passwd = data.get("passwd")
result = {"ret": EOK}
return json.dumps(result)
if __name__ == '__main__':
app.run(host='localhost', port=8080)
2、db資料庫操作
# -*- coding: utf-8 -*-
# 官方檔案
# https://pypi.org/project/records/
from os import name
import records
from retCode import *
# 連接資料庫
db = records.Database(
'mysql://root:jdb@127.0.0.1:3306/vpn')
def getUserById(id):
data = []
# 讀取資料庫
sql = 'select * from user where id = %s' % (id)
try:
rows = db.query(sql)
r = rows.first(as_dict=True)
data = [r["id"], r["account"], r["passwd"],
r["role"], r["alias"]]
except Exception as e:
print(e)
return data
def userList():
data = []
# 讀取資料庫
sql = "select * from user order by id desc"
try:
rows = db.query(sql)
for r in rows.all(as_dict=True):
data.append(
[r["id"], r["account"], r["role"], r["alias"], r["time"]])
except Exception as e:
print(e)
return data
def userAdd(data):
user = data
sql = 'insert into user(account, passwd, role, alias, time) values (:account, :passwd,:role,:alias,:time )'
try:
res = db.query(sql, **user)
if res.pending:
return EOK
except Exception as e:
print(e)
return EUserAddError
def userEdit(data):
user = data
sql = 'update user set account=:account, passwd=:passwd, role=:role, alias=:alias where id=:id'
try:
res = db.query(sql, **user)
if res.pending:
return EOK
except Exception as e:
print(e)
return EUserEditError
def userDel(id):
sql = 'delete from user where id=%s' % (id)
try:
res = db.query(sql)
if res.pending:
return EOK
except Exception as e:
print(e)
return EUserDelError
if __name__ == "__main__":
data = getUserById(13)
print(data)
六、啟動命令
1、開啟http服務
python main.py
2、瀏覽器操作
http://localhost:8080
附錄:參考資料
1、Bootstrap :Bootstrap5 教程 | 菜鳥教程
2、jQuery :jQuery API Documentation jQuery 教程 | 菜鳥教程
3、DataTables :DataTables | Table plug-in for jQuery
4、Python Flask:Welcome to Flask — Flask Documentation (2.0.x)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/400726.html
標籤:其他
上一篇:2022跨年煙花代碼
