当前位置:   article > 正文

资产信息管理系统-前后端开发_信息资产管理系统简单部署

信息资产管理系统简单部署

题目要求:

资产管理系统

利用H5规范,CSS样式与JS脚本独立于HTML页面,Javascript调用jQuery库,CRUD后端使用FastAPI封装,前端页面在Nginx中运行,调用API模块, 实现CURD的课设总结

基本设计:

后端:

前后端的对接可以通过 FastAPI 框架提供的 API 接口实现。
第一,在后端部分,使用 FastAPI 构建了一个封装了 CRUD 操作的 API 服务器。这个服务器可以接收来自前端的请求,并根据请求中的操作类型(如 POST、GET、PUT、DELETE 等)和数据来执行相应的操作。前端部分通过使用 HTML、CSS 和 JS 等技术构建了用户界面,包括 CRUD 操作的界面。这些界面可以通过浏览器或 Nginx 服务器提供给用户使用。

在前后端对接的过程中,前端页面可以通过 AJAX 或 Fetch API 等技术向 API 服务器发送请求。API 服务器接收请求后,根据请求中的操作类型和数据执行相应的操作,然后将结果返回给前端。前端接收到结果后,可以根据结果更新页面或做出相应的响应。



综上,通过 FastAPI 框架提供的 API 接口实现了前后端的对接。前端发送请求给 API 服务器,API 服务器处理请求并返回结果给前端,从而实现了前后端的交互和数据管理。

数据库:

资产表(Assets):
资产ID(AssetID):主键,自增长,类型为整数
资产名称(AssetName):资产名称,类型为字符串,长度为255
资产类型(AssetType):资产类型,类型为字符串,长度为50
购买日期(PurchaseDate):购买日期,类型为日期
购买价格(PurchasePrice):购买价格,类型为数值型,精度为两位小数
资产状态(AssetStatus):资产状态,类型为字符串,长度为50
其他相关字段...
用户表(Users):
用户ID(UserID):主键,自增长,类型为整数
用户名(Username):用户名,类型为字符串,长度为255
密码(Password):密码,类型为字符串,长度为255
姓名(Name):姓名,类型为字符串,长度为100
邮箱(Email):邮箱,类型为字符串,长度为100
其他相关字段...
操作记录表(OperationRecords):
记录ID(RecordID):主键,自增长,类型为整数
用户ID(UserID):操作用户ID,类型为整数
操作类型(OperationType):操作类型,类型为字符串,长度为50
操作时间(OperationTime):操作时间,类型为时间戳
其他相关字段...
main.py:

  1. # -*-coding:utf-8-*-
  2. from fastapi import FastAPI, HTTPException, Depends, Form
  3. from starlette.middleware.cors import CORSMiddleware
  4. from user import user_router
  5. from asset import asset_router
  6. from operation import op_router
  7. import uvicorn
  8. app = FastAPI()
  9. #三个路由,模块化,对应各自的路由
  10. app.include_router(user_router, prefix='/user')
  11. app.include_router(asset_router, prefix='/asset')
  12. app.include_router(op_router, prefix='/operation')
  13. # 添加跨域访问中间件
  14. app.add_middleware(
  15. CORSMiddleware,
  16. allow_origins=["http://127.0.0.1"],
  17. allow_credentials=True,
  18. allow_methods=["*"],
  19. allow_headers=["*"],
  20. )
  21. if __name__ == '__main__':
  22. uvicorn.run(app)

user.py:

  1. # -*-coding:utf-8-*-
  2. from datetime import datetime
  3. from fastapi import APIRouter, Query, Depends, Response
  4. from pydantic import BaseModel
  5. from sqlalchemy import select, func
  6. from sqlalchemy.orm import Session
  7. from tool import *
  8. from model import User
  9. #验证请求参数是否正确
  10. class UserParam(BaseModel):
  11. username: str
  12. phone: str
  13. birth: str
  14. email: str
  15. asset_count: int
  16. user_router = APIRouter()
  17. #请求到user/list则执行该函数
  18. @user_router.get('/list')#分页:
  19. def get_user_list(page: int = Query(1), keyword: str = Query(None), limit: int = Query(15),
  20. dbs: Session = Depends(get_db)):
  21. #以下通过dbs操作数据库
  22. if keyword is None:
  23. query = dbs.query(User)#是空,则声明一个查询
  24. else:
  25. query = dbs.query(User).filter((User.username.ilike(f"%{keyword}%")))
  26. total_count = query.with_entities(func.count(User.user_id)).scalar()
  27. #统计数据经行分页
  28. return {'code': 0, 'data': query.offset((page - 1) * limit).limit(limit).all(), 'count': total_count}
  29. #线偏移,限制和所有结果
  30. #请求post路径时,参数和数据在UserParam请求体中,相对get来说更安全一些,且数据没有上限,而get有上限
  31. @user_router.post('/add')
  32. def add_user(user: UserParam, dbs: Session = Depends(get_db)):
  33. try:
  34. new_user = User(**user.model_dump())
  35. #**代表解包,user.model_dump()整体代表字典
  36. #解包:a(**{'a':1})==a(a==1)
  37. #创建一个新操作保存操作记录
  38. new_operation = OperationRecord(
  39. **{"user_id": new_user.user_id, "username": new_user.username, "operation_type": "添加用户",
  40. "operation_time": datetime.now()})
  41. for key, value in user.model_dump().items():
  42. #判断是否是日期的格式,如果是则转换成datatime对象
  43. if key == 'birth':
  44. setattr(new_user, key, datetime.strptime(value, '%Y-%m-%d'))
  45. else:
  46. setattr(new_user, key, value)
  47. dbs.add(new_user)
  48. dbs.flush()#刷新
  49. dbs.add(new_operation)
  50. dbs.commit()
  51. return {'code': 0}#正确
  52. except Exception:
  53. return Response(status_code=404)
  54. #路径/user/modify?user_id=2
  55. #此处与之前相比多了一个user_id参数
  56. @user_router.post('/modify')
  57. def modify_user(user: UserParam, user_id: int = Query(...), dbs: Session = Depends(get_db)):
  58. try:
  59. user_modify = dbs.query(User).filter(User.user_id == user_id).first()
  60. #用user_id查询
  61. new_operation = OperationRecord(
  62. **{"user_id": user_modify.user_id, "username": user_modify.username, "operation_type": "修改用户",
  63. "operation_time": datetime.now()})
  64. if user_modify is None:
  65. raise HTTPException(status_code=404, detail="User not found")
  66. for key, value in user.model_dump().items():
  67. if 'birth' == key:
  68. setattr(user_modify, key, datetime.strptime(value, '%Y-%m-%d'))
  69. else:
  70. setattr(user_modify, key, value)
  71. dbs.add(new_operation)
  72. dbs.commit()#直接提交到数据库
  73. return {'code': 0}#正确结束
  74. except Exception:
  75. return Response(status_code=404)
  76. @user_router.get('/del')
  77. #...代表必要要有query,否则返回错误,即:不可以/user/del直接请求,而是/user/del?user_id=
  78. def del_user(user_id: int = Query(...), dbs: Session = Depends(get_db)):
  79. db_user = dbs.query(User).filter(User.user_id == user_id).first()
  80. new_operation = OperationRecord(
  81. **{"user_id": db_user.user_id, "username": db_user.username, "operation_type": "删除用户",
  82. "operation_time": datetime.now()})
  83. if db_user is None:
  84. raise HTTPException(status_code=404, detail="User not found")
  85. dbs.delete(db_user)
  86. dbs.add(new_operation)
  87. dbs.commit()
  88. return {'code': 0}

 tool.py:

  1. # -*-coding:utf-8-*-
  2. from datetime import timedelta, datetime
  3. from typing import Optional
  4. from fastapi import Cookie, HTTPException, Header
  5. from sqlalchemy import create_engine
  6. from sqlalchemy.orm import sessionmaker
  7. from model import *
  8. # 在数据库中创建表
  9. Base.metadata.create_all(engine)#engine相当于数据库
  10. session_maker = sessionmaker(autocommit=False, autoflush=False, bind=engine)
  11. #返回一个数据库操作接口
  12. def get_db():
  13. db = session_maker()#数据库库接口
  14. try:
  15. yield db
  16. finally:
  17. db.close()

 model.py:

  1. # -*-coding:utf-8-*-
  2. from sqlalchemy import create_engine, Column, Integer, String, Numeric, Date, DateTime, ForeignKey
  3. from sqlalchemy.ext.declarative import declarative_base
  4. from sqlalchemy.orm import relationship
  5. #该orm框架应用很广泛
  6. # 创建数据库连接
  7. engine = create_engine('sqlite:///shiyan.db')
  8. #创建引擎
  9. # 创建一个基类
  10. Base = declarative_base()
  11. #创建表的类后不需要用sql语句创建
  12. # 定义用户表(Users)
  13. class User(Base):#三个表继承基类创建
  14. __tablename__ = 'users'
  15. user_id = Column(Integer, primary_key=True, autoincrement=True)
  16. username = Column(String(255))
  17. phone = Column(String(255))
  18. birth = Column(Date)
  19. email = Column(String(100))
  20. asset_count = Column(Integer)
  21. # 定义资产表(Assets)
  22. class Asset(Base):
  23. __tablename__ = 'assets'
  24. asset_id = Column(Integer, primary_key=True, autoincrement=True)
  25. asset_name = Column(String(255))
  26. asset_type = Column(String(50))
  27. purchase_date = Column(Date)
  28. purchase_price = Column(Numeric(10, 2))
  29. asset_status = Column(String(50))
  30. user_id = Column(Integer, ForeignKey('users.user_id'))#外键
  31. # 定义操作记录表(OperationRecords)
  32. class OperationRecord(Base):
  33. __tablename__ = 'operation_records'
  34. record_id = Column(Integer, primary_key=True, autoincrement=True)
  35. user_id = Column(Integer, nullable=True)
  36. username = Column(String(255), nullable=True)
  37. asset_id = Column(Integer, nullable=True)
  38. asset_name = Column(String(255), nullable=True)
  39. operation_type = Column(String(50))
  40. operation_time = Column(DateTime)

asset.py:

  1. # -*-coding:utf-8-*-
  2. from datetime import datetime
  3. from fastapi import APIRouter, Query, Depends, Response
  4. from pydantic import BaseModel
  5. from sqlalchemy import select, func
  6. from sqlalchemy.orm import Session
  7. from tool import *
  8. from model import Asset
  9. class AssetParam(BaseModel):
  10. asset_name: str
  11. asset_type: str
  12. purchase_date: str
  13. purchase_price: str
  14. asset_status: str
  15. user_id: int
  16. asset_router = APIRouter()
  17. @asset_router.get('/list')
  18. def get_asset_list(page: int = Query(1), limit: int = Query(15), keyword: str = Query(None),
  19. dbs: Session = Depends(get_db)):
  20. if keyword is None:
  21. query = dbs.query(Asset.asset_id, Asset.asset_name, Asset.asset_type, Asset.asset_status, Asset.purchase_date,
  22. Asset.purchase_price, User.user_id, User.username).where(Asset.user_id == User.user_id)
  23. else:
  24. query = dbs.query(Asset.asset_id, Asset.asset_name, Asset.asset_type, Asset.asset_status, Asset.purchase_date,
  25. Asset.purchase_price, User.user_id, User.username).where(
  26. Asset.user_id == User.user_id).filter((Asset.asset_name.ilike(f"%{keyword}%")))#ilike模糊查询
  27. total_count = query.with_entities(func.count(Asset.asset_id)).scalar()
  28. return {'code': 0, 'data': query.offset((page - 1) * limit).limit(limit).all(), 'count': total_count}
  29. @asset_router.post('/add')
  30. def add_user(asset: AssetParam, dbs: Session = Depends(get_db)):
  31. try:
  32. new_asset = Asset(**asset.model_dump())
  33. user_modify = dbs.query(User).filter(User.user_id == asset.user_id).first()
  34. if user_modify is not None:
  35. for key, value in asset.model_dump().items():
  36. if 'date' in key:
  37. setattr(new_asset, key, datetime.strptime(value, '%Y-%m-%d'))
  38. else:
  39. setattr(new_asset, key, value)
  40. new_operation = OperationRecord(
  41. **{"user_id": user_modify.user_id, "username": user_modify.username, "asset_id": new_asset.asset_id,
  42. "asset_name": new_asset.asset_name, "operation_type": "添加资产", "operation_time": datetime.now()})
  43. user_modify.asset_count += 1#资产增加了对应的用户的资产数量也增加
  44. dbs.add(new_asset)
  45. dbs.add(new_operation)
  46. dbs.commit()
  47. return {'code': 0}
  48. else:
  49. return Response(status_code=404)
  50. except Exception:
  51. return Response(status_code=404)
  52. @asset_router.post('/modify')
  53. def modify_asset(asset: AssetParam, asset_id: int = Query(...), dbs: Session = Depends(get_db)):
  54. try:
  55. asset_modify = dbs.query(Asset).filter(Asset.asset_id == asset_id).first()
  56. old_user_modify = dbs.query(User).filter(User.user_id == asset_modify.user_id).first()
  57. new_user_modify = dbs.query(User).filter(User.user_id == asset.user_id).first()
  58. if asset_modify is None or new_user_modify is None:
  59. raise HTTPException(status_code=404, detail="Asset not found")
  60. for key, value in asset.model_dump().items():
  61. if 'date' in key:
  62. setattr(asset_modify, key, datetime.strptime(value, '%Y-%m-%d'))
  63. else:
  64. setattr(asset_modify, key, value)
  65. new_operation = OperationRecord(
  66. **{"user_id": old_user_modify.user_id, "username": old_user_modify.username,
  67. "asset_id": asset_modify.asset_id,
  68. "asset_name": asset_modify.asset_name, "operation_type": "修改资产", "operation_time": datetime.now()})
  69. old_user_modify.asset_count -= 1#资产拥有者改变,相应的拥有者资产数量改变
  70. new_user_modify.asset_count += 1
  71. dbs.add(new_operation)
  72. dbs.commit()
  73. return {'code': 0}
  74. except Exception:
  75. return Response(status_code=404)
  76. @asset_router.get('/sell')
  77. def sell_user(asset_id: int = Query(...), dbs: Session = Depends(get_db)):
  78. db_asset = dbs.query(Asset).filter(Asset.asset_id == asset_id).first()
  79. user_modify = dbs.query(User).filter(User.user_id == db_asset.user_id).first()
  80. if db_asset is None:
  81. raise HTTPException(status_code=404, detail="Asset not found")
  82. new_operation = OperationRecord(
  83. **{"user_id": user_modify.user_id, "username": user_modify.username, "asset_id": db_asset.asset_id,
  84. "asset_name": db_asset.asset_name, "operation_type": "售出资产", "operation_time": datetime.now()})
  85. user_modify.asset_count -= 1
  86. dbs.delete(db_asset)
  87. dbs.add(new_operation)
  88. dbs.commit()
  89. return {'code': 0}

operation.py:

  1. # -*-coding:utf-8-*-
  2. from fastapi import APIRouter, Query, Depends
  3. from sqlalchemy import select, func
  4. from sqlalchemy.orm import Session
  5. from tool import *
  6. from model import *
  7. op_router = APIRouter()
  8. @op_router.get('/list')
  9. def get_op_list(page: int = Query(1), limit: int = Query(15), dbs: Session = Depends(get_db)):
  10. query = dbs.query(OperationRecord)
  11. total_count = query.with_entities(func.count(OperationRecord.record_id)).scalar()
  12. return {'code': 0, 'data': query.offset((page - 1) * limit).limit(limit).all(), 'count': total_count}

资产表页面:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>layui</title>
  6. <meta name="renderer" content="webkit">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  8. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  9. <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  10. <link rel="stylesheet" href="../css/public.css" media="all">
  11. </head>
  12. <body>
  13. <div class="layuimini-container">
  14. <div class="layuimini-main">
  15. <fieldset class="table-search-fieldset">
  16. <legend>搜索信息</legend>
  17. <div style="margin: 10px 10px 10px 10px">
  18. <form class="layui-form layui-form-pane" action="">
  19. <div class="layui-form-item">
  20. <div class="layui-inline">
  21. <label class="layui-form-label">名称</label>
  22. <div class="layui-input-inline">
  23. <input type="text" name="name" autocomplete="off" class="layui-input">
  24. </div>
  25. </div>
  26. <div class="layui-inline">
  27. <button type="submit" class="layui-btn layui-btn-primary" lay-submit
  28. lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
  29. </button>
  30. </div>
  31. </div>
  32. </form>
  33. </div>
  34. </fieldset>
  35. <script type="text/html" id="toolbarDemo">
  36. <div class="layui-btn-container">
  37. <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加</button>
  38. </div>
  39. </script>
  40. <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
  41. <script type="text/html" id="currentTableBar">
  42. <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
  43. <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">售出</a>
  44. </script>
  45. </div>
  46. </div>
  47. <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
  48. <script>
  49. layui.use(['form', 'table'], function () {
  50. var $ = layui.jquery,
  51. form = layui.form,
  52. table = layui.table;
  53. table.render({
  54. elem: '#currentTableId',
  55. url: 'http://127.0.0.1:8000/asset/list',
  56. toolbar: '#toolbarDemo',
  57. defaultToolbar: ['filter', 'exports', 'print', {
  58. title: '提示',
  59. layEvent: 'LAYTABLE_TIPS',
  60. icon: 'layui-icon-tips'
  61. }],
  62. cols: [[
  63. {type: "checkbox", width: 50},
  64. {field: 'asset_id', width: 80, title: 'ID', sort: true},
  65. {field: 'asset_name', width: 100, title: '资产名称'},
  66. {field: 'asset_type', width: 100, title: '资产类型', sort: true},
  67. {field: 'purchase_date', width: 150, title: '购买日期', sort: true},
  68. {field: 'purchase_price', title: '购买单价', width: 100, sort: true},
  69. {field: 'asset_status', title: '购买数量', width: 100, sort: true},
  70. {field: 'user_id', title: '所属用户ID', width: 100},
  71. {field: 'username', title: '所属用户名称', width: 150},
  72. {title: '操作', width: 250, toolbar: '#currentTableBar', align: "center"}
  73. ]],
  74. limits: [10, 15, 20, 25, 50, 100],
  75. limit: 15,
  76. page: true,
  77. skin: 'line'
  78. });
  79. // 监听搜索操作
  80. form.on('submit(data-search-btn)', function (data) {
  81. //执行搜索重载
  82. table.reload('currentTableId', {
  83. page: {
  84. curr: 1
  85. }
  86. , where: {
  87. keyword: data.field.name
  88. }
  89. }, 'data');
  90. return false;
  91. });
  92. /**
  93. * toolbar监听事件,点击按钮时触发
  94. */
  95. table.on('toolbar(currentTableFilter)', function (obj) {
  96. if (obj.event === 'add') { // 监听添加操作
  97. var index = layer.open({
  98. title: '添加资产',
  99. type: 2,
  100. shade: 0.2,
  101. maxmin: true,
  102. shadeClose: true,
  103. area: ['90%', '90%'],
  104. content: '../page/table/edit-asset.html',#打开修改资产网页
  105. });
  106. $(window).on("resize", function () {
  107. layer.full(index);
  108. });
  109. }
  110. });
  111. table.on('tool(currentTableFilter)', function (obj) {
  112. var data = obj.data;
  113. if (obj.event === 'edit') {
  114. var index = layer.open({
  115. title: '编辑资产',
  116. type: 2,
  117. shade: 0.2,
  118. maxmin: true,
  119. shadeClose: true,
  120. area: ['90%', '90%'],
  121. content: '../page/table/edit-asset.html',
  122. success: function (layero, index) {
  123. let body = layer.getChildFrame('body', index);
  124. body.find("#asset_id").val(data.asset_id);
  125. body.find("#asset_name").val(data.asset_name);
  126. body.find("#asset_type").val(data.asset_type);
  127. body.find("#purchase_date").val(data.purchase_date);
  128. body.find("#purchase_price").val(data.purchase_price);
  129. body.find("#asset_status").val(data.asset_status);
  130. body.find("#user_id").val(data.user_id);
  131. layui.form.render();
  132. },
  133. end: function () {//重载表格
  134. table.reload('currentTableId', {
  135. page: {
  136. curr: 1
  137. }
  138. , where: {}
  139. }, 'data');
  140. return false;
  141. }
  142. });
  143. $(window).on("resize", function () {
  144. layer.full(index);
  145. });
  146. return false;
  147. } else if (obj.event === 'delete') {
  148. layer.confirm('真的售出资产吗', function (index) {
  149. $.ajax({
  150. url: 'http://127.0.0.1:8000/asset/sell?asset_id=' + data.asset_id,
  151. method: 'GET',
  152. success: function (response) {
  153. obj.del();
  154. layer.close(index);
  155. },
  156. error: function (error) {
  157. layer.alert(error);
  158. }
  159. });
  160. });
  161. }
  162. });
  163. });
  164. </script>
  165. </body>
  166. </html>

资产编辑页面:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>layui</title>
  6. <meta name="renderer" content="webkit">//用webkit引擎渲染
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  8. //提示浏览器用最新的渲染模式
  9. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  10. <link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
  11. <link rel="stylesheet" href="../../css/public.css" media="all">
  12. <style>
  13. body {
  14. background-color: #ffffff;//设置网页背景为白色
  15. }
  16. </style>
  17. </head>
  18. <body>
  19. <div class="layui-form layuimini-form">
  20. <div class="layui-form-item">
  21. <div class="layui-input-block">
  22. <input type="number" name="asset_id" value="-1" class="layui-input" style="display: none"
  23. id="asset_id">
  24. </div>
  25. </div>
  26. <div class="layui-form-item required">
  27. <label class="layui-form-label required">资产名</label>
  28. <div class="layui-input-block">
  29. <input type="text" name="asset_name" lay-verify="required"
  30. placeholder="请输入资产名" value="" class="layui-input" id="asset_name">
  31. </div>
  32. </div>
  33. <div class="layui-form-item">
  34. <label class="layui-form-label required">资产类型</label>
  35. <div class="layui-input-block">
  36. <input type="text" name="asset_type" lay-verify="required" placeholder="请输入资产类型"
  37. value="" class="layui-input" id="asset_type">
  38. </div>
  39. </div>
  40. <div class="layui-form-item">
  41. <label class="layui-form-label required">购买日期</label>
  42. <div class="layui-input-block">
  43. <input type="date" name="purchase_date" placeholder="请选择购买日期" value=""
  44. class="layui-input" lay-verify="required" id="purchase_date">
  45. </div>
  46. </div>
  47. <div class="layui-form-item">
  48. <label class="layui-form-label required">购买价格</label>
  49. <div class="layui-input-block">
  50. <input type="text" name="purchase_price" placeholder="请输入购买价格" lay-verify="required" value=""
  51. class="layui-input" id="purchase_price">
  52. </div>
  53. </div>
  54. <div class="layui-form-item">
  55. <label class="layui-form-label required">资产状态</label>
  56. <div class="layui-input-block">
  57. <input type="text" name="asset_status" placeholder="请输入资产状态" lay-verify="required"
  58. class="layui-input" id="asset_status">
  59. </div>
  60. </div>
  61. <div class="layui-form-item">
  62. <label class="layui-form-label required">所属用户</label>
  63. <div class="layui-input-block">
  64. <input type="number" name="user_id" placeholder="请输入资产所属用户" lay-verify="required"
  65. class="layui-input" id="user_id">
  66. </div>
  67. </div>
  68. <div class="layui-form-item">
  69. <div class="layui-input-block">
  70. <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
  71. </div>
  72. </div>
  73. </div>
  74. </div>
  75. <script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
  76. <script>
  77. layui.use(['form'], function () {
  78. var form = layui.form,
  79. layer = layui.layer,
  80. $ = layui.$;
  81. //监听提交
  82. form.on('submit(saveBtn)', function (data) {
  83. $.ajax({
  84. url: data.field.asset_id === "-1" ? "http://127.0.0.1:8000/asset/add" : ("http://127.0.0.1:8000/asset/modify?asset_id=" + data.field.asset_id + "&user_id=" + data.field.user_id),
  85. method: 'POST',
  86. contentType: 'application/json',
  87. data: JSON.stringify(data.field),
  88. success: function (response) {
  89. layer.alert("操作成功!", function () {
  90. var iframeIndex = parent.layer.getFrameIndex(window.name);
  91. parent.layer.close(iframeIndex);
  92. })
  93. },
  94. error: function (error) {
  95. alert(error);
  96. }
  97. });
  98. return false;
  99. });
  100. });
  101. </script>
  102. </body>
  103. </html>

操作页面:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="utf-8">
  5. <title>layui</title>
  6. <meta name="renderer" content="webkit">
  7. <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  8. <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  9. <link rel="stylesheet" href="../lib/layui-v2.6.3/css/layui.css" media="all">
  10. <link rel="stylesheet" href="../css/public.css" media="all">
  11. </head>
  12. <body>
  13. <div class="layuimini-container">
  14. <div class="layuimini-main">
  15. <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
  16. <script type="text/html" id="currentTableBar">
  17. <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
  18. <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
  19. </script>
  20. </div>
  21. </div>
  22. <script src="../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
  23. <script>
  24. layui.use(['form', 'table'], function () {
  25. var $ = layui.jquery,
  26. form = layui.form,
  27. table = layui.table;
  28. table.render({//渲染
  29. elem: '#currentTableId',
  30. url: 'http://127.0.0.1:8000/operation/list',
  31. toolbar: '#toolbarDemo',
  32. defaultToolbar: ['filter', 'exports', 'print', {
  33. title: '提示',
  34. layEvent: 'LAYTABLE_TIPS',
  35. icon: 'layui-icon-tips'
  36. }],
  37. cols: [[
  38. {type: "checkbox", width: 50},
  39. {field: 'record_id', width: 120, title: '记录ID', sort: true},
  40. {field: 'username', width: 200, title: '用户'},
  41. {field: 'asset_name', width: 200, title: '资产'},
  42. {field: 'operation_type', title: '操作类型'},
  43. {field: 'operation_time', title: '操作时间', sort: true},
  44. ]],
  45. limits: [10, 15, 20, 25, 50, 100],
  46. limit: 15,
  47. page: true,
  48. skin: 'line'
  49. });
  50. });
  51. </script>
  52. </body>
  53. </html>

 Uvicon服务器正在监听127.0.0.1的8000端口

 127.0.0.1也称为localhost,表示计算机本身地址

效果图

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/995120
推荐阅读
相关标签
  

闽ICP备14008679号