Measuring open the road to one hundred fifty-four: ajax + json foreground and data exchange

 

In practice, the front and rear ends are used in most of the data exchange format json, after the rear end of the data processing, the pass json distal tip then parsed

Project structure

models which join method into the data dictionary

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 'employees: self.id {} {} {self.salary the self.name self.address} {}'

DEF the to_json (Self):
"" "for subsequent transfer to the content SQLAlchemy json objects" ""
return dict (self.id ID =, = the self.name name, address = self.address, the salary = self.salary)


IF the __name__ == '__main__':
db.create_all ()

emp-json.html

<!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 () { Success: function (depts) { dataType: ' JSON ', Method,: 'GET', url: '/ Department /', $ .ajax ({
after // page ready to put the information department found out, and rendered to the sector inside the drop-down list





$.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 ( ''); // clear the contents of the id emp-list, prevent duplicate rendering
// If the rear end back to the state 0, i.e. the data, the data analysis proceeds rendered
IF (DATAS [ 'Status'] == 0) {
var table_header =' <Table border = ". 1"> <TR> < th> ID </ th> < th> name </ th> <th> address </ th> <th> salary </ 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.py

Import the Flask Flask from, the render_template, Request, jsonify 
from flask_sqlalchemy Import SQLAlchemy
from the Employee personal.models Import, Department

App = the Flask (__ name__, static_url_path = '')
DB = SQLAlchemy (App)

the app.config [ 'SQLALCHEMY_DATABASE_URI'] = 'SQLite : ///./db/test.db '# and address database type declaration
app.config [' SQLALCHEMY_TRACK_MODIFICATIONS '] = True # track changes


# app.config [' SQLALCHEMY_ECHO '] = True # corresponding print sql, this with sql how the kind of


returns department information #
@ app.route ( '/ department /')
DEF get_department ():
"" "a single case of
the dept = Department.query.first ()
return jsonify (dept.to_json ())
"" "
# multiple cases
depts = Department.query.all()
jsonify return ([d.to_json () for d in depts])


@ app.route ( '/ emp-info /')
DEF emp_info ():
"" "
1, obtained from the address bar to query the department staff good name
2, according to department and employee name, employee information to obtain
3, return information json format
"" "
name = request.args.get ( 'name', '')
the dept = request.args.get ( 'department', '' )
# = db.session.query DATAS (the Employee) .filter (Employee.name == name, Employee.department_id == Dept)
DATAS = db.session.query (the 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)

Data information:

access

valid data

Invalid data, it is cleared content, not rendered

 

Guess you like

Origin www.cnblogs.com/zhongyehai/p/11569249.html