測開之路一百五十四:ajax+json先後臺數據交互

 

在實際工做中,先後端數據交互大部分都是用的json格式,後端把數據處理完後,把json傳給前端,前端再解析css

項目結構html

models裏面加入把數據轉爲字典的方法前端

from datetime import datetime
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()


class Department(db.Model):
""" 部門 """
__tablename__ = 'department'
# primary_key=True:主鍵, autoincrement=True:自動遞增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50), unique=True)

def __init__(self, name):
self.name = name

def __repr__(self):
return f'部門{self.id},{self.name}'

def to_json(self):
""" 用於後面把SQLAlchemy的內容轉成json對象 """
return dict(id=self.id, name=self.name)


class Employee(db.Model):
""" 員工 """
__tablename__ = 'employee'
# primary_key=True:主鍵, autoincrement=True:自動遞增
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(50))
gender = db.Column(db.String)
job = db.Column(db.String)
birthdate = db.Column(db.Date)
idcard = db.Column(db.String)
address = db.Column(db.String)
salary = db.Column(db.Float)
release_time = db.Column(db.DateTime)

# 外鍵: db.Column(db.Integer, db.ForeignKey(表名))
department_id = db.Column(db.Integer, db.ForeignKey('department.id')) # 聲明是外鍵,爲department表的id字段

# db.relationship('Department', backref=db.backref('employee', lazy='dynamic'))
# db.relationship(主鍵類名, backref=引用屬性名, lazy='dynamic'))
# lazy:延遲查詢:dynamic:動態、select、subquery、joined
department = db.relationship('Department', backref=db.backref('employee', lazy='dynamic')) # 類與表的關係

def __init__(self, name=None, gender=None, job=None, birthdate=None, idcard=None, address=None, salary=None,
release_time=None):
self.name = name
self.gender = gender
self.job = job
self.birthdate = birthdate
self.idcard = idcard
self.address = address
self.salary = salary
self.release_time = release_time if release_time else datetime.now()

def __repr__(self):
return f'員工:{self.id} {self.name} {self.salary} {self.address}'

def to_json(self):
""" 用於後面把SQLAlchemy的內容轉成json對象 """
return dict(id=self.id, name=self.name, address=self.address, salary=self.salary)


if __name__ == '__main__':
db.create_all()

emp-json.htmljquery

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>josn數據</title>
<script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
</head>
<body>
部門:<select name="部門" id="department"></select>
姓名:<input type="text" id="name">
<input type="button" value="點擊查詢" id="btnSearch">
<div id="emp-list"></div>
</body>
</html>
<script>
$(document).ready(function () {
// 頁面準備好以後就把部門的信息查出來,並渲染到部門的下拉列表裏面
$.ajax({
url: '/department/',
method: 'GET',
dataType: 'json',
success: function (depts) {
$.each(depts, function (i, item) {
$('#department').append('<option value="' + item.id + '">' + item.name + '</option>');
});
}
});

// 查詢按鈕點擊事件
$('#btnSearch').click(function () {
var dept_id = $('#department').val();
var name = $('#name').val();
$.ajax({
url: '/emp-info/',
method: 'GET',
data: {'name': name, 'department': dept_id},
success: function (datas) {
$('#emp-list').html(''); // 清空id爲emp-list下的內容,防止重複渲染
// 若是後端返回來的狀態是0,即有數據,就進行數據解析渲染
if (datas['status']==0) {
var table_header = '<table border="1"><tr><th>ID</th><th>姓名</th><th>地址</th><th>工資</th></tr>';
var rows = "";
$.each(datas['datas'], function (i, data) {
rows += '<tr><td>' + data.id + '</td><td>' + data.name + '</td><td>' + data.address + '</td><td>' + data.salary + '</td></tr>';
$('#emp-list').html(table_header + rows + '</table>');
});
}
}
});

});
});
</script>

main.pyajax

from flask import Flask, render_template, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from personal.models import Employee, Department

app = Flask(__name__, static_url_path='')
db = SQLAlchemy(app)

app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///./db/test.db' # 聲明數據庫類型和地址
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True # 跟蹤改變


# app.config['SQLALCHEMY_ECHO'] = True # 打印對應的sql,此操做用sql是怎麼樣的


# 返回部門信息
@app.route('/department/')
def get_department():
""" 單個的狀況
dept = Department.query.first()
return jsonify(dept.to_json())
"""
# 多個的狀況
depts = Department.query.all()
return jsonify([d.to_json() for d in depts])


@app.route('/emp-info/')
def emp_info():
"""
一、從地址欄獲取要查詢的的部門好好員工名
二、根據部門和員工名,獲取員工信息
三、返回json格式的信息
"""
name = request.args.get('name', '')
dept = request.args.get('department', '')
# datas = db.session.query(Employee).filter(Employee.name == name, Employee.department_id == dept)
datas = db.session.query(Employee).filter(Employee.name == name).filter(Employee.department_id == dept)
if datas:
return jsonify({
'status': 0,
'datas': [d.to_json() for d in datas]
})
return jsonify({
'status': 1,
'datas': []
})


@app.route('/emp-json/')
def emp_json():
return render_template('emp-json.html')


if __name__ == '__main__':
app.run(debug=True)

數據信息:sql

訪問數據庫

有效數據json

無效數據,會清空內容,並不渲染flask

相關文章
相關標籤/搜索