乐趣区

关于flask:flask-layui-联动选择框-实例

  • 图 1
  • 图 2
  • 图 3

orm


class Select(db.Model):
    __tablename__ = 'select_project'  # 表名
    select_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    select_name = db.Column(db.String(200), nullable=False)  # 分类名称、不能为空
    roles = db.Column(db.Integer, nullable=False)  # 级别、不能为空

    def single_to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

    def to_dict(self):
        model_dict = dict(self.__dict__)
        del model_dict['_sa_instance_state']
        return model_dict


class Resources(db.Model):
    __tablename__ = 'resources'  # 表名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    resources_name = db.Column(db.String(200), nullable=False)  # 分类名称、不能为空
    parent_id = db.Column(db.Integer, nullable=False)  # 父级 id、不能为空。###obj 转 json
def to_json_all(msg: list):
    import json
    data = {}
    if type(msg) == list:
        for i in range(len(msg)):
            temp_dict = {}
            j = 0
            for k, v in msg[i].__dict__.items():
                if j > 0:
                    temp_dict[k] = v
                j += 1

            data[i] = temp_dict
    else:
        temp_dict = {}
        j = 0
        for k, v in msg.__dict__.items():
            if j > 0:
                temp_dict[k] = v
            j += 1
        data[0] = temp_dict
    return json.dumps(data, ensure_ascii=False)



  • select_project
  • resources

view


@silence.route('/silence_add', methods=['GET'])
@silence.route('/silence_add/', methods=['GET'])
@login_required
@permission_required(Permission.AVERAGE_USER)
def silence_add1():
    return render_template('silence_add.html', select_project=Select.query.all())

@silence.route('/select_project/', methods=['POST'])
def select_project1():
    select_id = request.form.get('select_id')  # 接管 ajax 提交的数据 -- 地区 id
    print("##id", select_id)
    resources_obj = Resources.query.filter_by(parent_id=select_id).all()
    #resources_json = resources_obj.single_to_dict()
    data = to_json_all(resources_obj)  # 打包成成 json 格局
    print("##data", data)

    return data

html




        <div class="layui-form-item">
            <label class="layui-form-label">project</label>
            <div class="layui-input-block">
                <select name="village" lay-filter="village" lay-verify="required" lay-search>
                    <option value=""></option>
                    {% for village in select_project %}
                        <option value="{{village.select_id}}">{{village.select_name}}</option>
                    {% endfor %}
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">Values</label>
            <div class="layui-input-block">
                <select name="locationtest" id="locationtest" lay-filter="locationtest" lay-verify="required"
                        lay-search>
                    <option value=""></option>

                </select>
            </div>
        </div>








js

    <script>
        layui.use(['layer', 'jquery', 'form'], function () {
            var layer = layui.layer,
                $ = layui.jquery,
                form = layui.form; // 不写下拉框加载不进去


            form.on('select(village)', function (data) {if (data.value != '') {console.log(data.value);  // 打印获取到的值 ---- 地区 value 值
                    locationtest(data.value);   // 调用 locationtest 办法, 参数是获取到的地区 value 值
                }
            });


            function locationtest(village) {
                var url = '/select_project/';  // 解决地址 url
                var data = {'select_id': village};  // 提交到先天的数据 -- 地区 value 值 -- 地区 id
                $.ajax({
                    type: 'post',
                    url: url,
                    data: data,
                    dataType: 'json',
                    success: function (data) {
                        var html = '<option value=""></option>';  // 将下拉框清空从新填写新的内容
                        $.each(data, function (key, obj) { // each 便当 django 返回的 json 数据, 并用拼接字符串的模式动静加载到下拉框
                            html += '<option value="+ obj.id +">' + obj.resources_name + '</option>'
                        });
                        $('[name=locationtest]').html(html);
                        // -----①  见下方阐明处
                        form.render('select');  // 从新渲染
                        // -----
                    }
                });
            }


        });


    </script>
退出移动版