Flask中如何从后端视图函数传递多个值给前端JS

背景

使用Bootstrap-table加载表格,需要从前端发起加载,从后端传递结果和Columns。

目标

实现后端向前端传递结果df(从数据库获得)和相应的Columns(用于前端展示,Field较多,不想前端Hardcoding)

方案

在后端采用字典写法,前端JS用点运算符获取即可。

后端

@app.route('/NDF/getMaintable', methods=['POST','GET'])
def getMaintable():
    if session.get("user_name")==None:
        return render_template("404.html")
    filter_mode = request.form['filter_mode']

    result = get_query_table(filter_mode)[0]
    head_list = result.columns
    col_dict_list = [{"field": x, "title": x, "halign": 'center', "align": "center", "sortable": 1,"width": 200} if x == "fCNName" else {"field": x, "title": x, "halign": 'center',"align": "center", "sortable": 1, "width": 100} for x in head_list]
    rows = result.to_json(orient='records')
    return {'rows':rows,'cols':str(col_dict_list)}

前端JS

            function load(cur_status){

            $.ajaxSetup({async:false})
            $.post('/NDF/getMaintable', {filter_mode:cur_status}, function(data){cur_data = data})
            $("#table1").bootstrapTable({
            data:JSON.parse(cur_data.rows),
            search: true,
            singleSelect: true,
            toolbar:'#toolbar',
            pagination: true,
            pageSize: 10,
            pageList: [5, 10, 15,20,50,100],
            showColumns: true,
            showRefresh: true,
            showToggle: true,
            locale: "zh-CN",
            clickToSelect:true,
            stickytableheader:true,
            striped: true,
            method: 'get',
            columns: eval(cur_data.cols)
            });
        }

结果

As Expected

上一篇:flask框架-使用flask-migrate进行数据库的管理,非常方便!!!


下一篇:Flask Error:ModuleNotFoundError: No module named ‘flask._compat‘