• 测开之路一百五十三:ajax之load、get、ajax在项目中的体现


    在查询的时候是使用ajax进行请求的

    目录结构

    personal.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}'


    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}'


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

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script>
    <title>ajax员工查询</title>
    </head>
    <body>
    <h1>ajax员工查询</h1>
    名称:<input type="text" id="name">
    <p>
    <button id="btnLoad">Load查询员工</button>
    <button id="btnGet">GET查询员工</button>
    <button id="btnAjax">ajax查询员工</button>
    </p>
    <div id="emp-list"></div>
    </body>
    </html>
    <script>
    $(document).ready(function () {

    // load方法
    $('#btnLoad').click(function () {
    var name = $('#name').val(); // 获取查询条件
    $('#emp-list').load('/employee/?name=' + name); // 把查询条件和地址拼接起来
    });

    // get方法
    $('#btnGet').click(function () {
    var name = $('#name').val(); // 获取查询条件
    $.get(
    '/employee/',
    {'name': name},
    function (response) {
    $('#emp-list').html(response); // 把返回的html加到id为emp-list的标签下
    }
    );
    });

    // ajax方法
    $('#btnAjax').click(function () {
    $.ajax({
    url: '/employee/',
    data: {'name': $('#name').val()},
    method: 'GET',
    success: function (response) {
    $('#emp-list').html(response); // 把返回的html加到id为emp-list的标签下
    }
    });
    });
    });
    </script>

    main.py

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

    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('/employee/')
    def employee_query():
    """ 这里图省事,就根据前端出过来的值,进行查询,并把查询出来的结果拼接成表格返回到前端 """
    name = request.args.get('name', '')
    table_header = """
    <table border="1">
    <tr>
    <th>ID</th>
    <th>姓名</th>
    <th>地址</th>
    <th>工资</th>
    </tr>
    """
    emps = Employee.query.filter(Employee.name.contains(name)).all()
    rows = ""
    for emp in emps:
    rows += f"""<tr><td>{emp.id}</td><td>{emp.name}</td><td>{emp.address}</td><td>{emp.salary}</td></tr>"""
    table_footer = "</table>"
    return table_header + rows + table_footer


    @app.route('/ajax_query/')
    def ajax_query():
    return render_template('emp-query.html')

    前端

    load

    get

    ajax

  • 相关阅读:
    回归,随缘写一些python心得吧
    划分树【有些东西,其实自己还不太会也要忍住把*装完】
    [codevs3273]两圆的交 计算几何
    10-12考试整理
    10-7考试整理
    [codevs1163]访问艺术馆
    [codevs2640]打印页数
    9-28 解题报告
    [CODEVS3323]时空跳跃者的封锁
    [codevs2442] kshort 经典题
  • 原文地址:https://www.cnblogs.com/zhongyehai/p/11565452.html
Copyright © 2020-2023  润新知