其他分享
首页 > 其他分享> > Flask中如何从后端视图函数传递多个值给前端JS

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

标签:cur,从后,Flask,true,前端,list,视图,mode,data
来源: https://blog.csdn.net/weixin_41697242/article/details/121213818