从Ajax响应动态创建表

时间:2017-11-20 10:35:24

标签: jquery python ajax flask

我有一个Flask应用程序,它根据AJAX调用返回JSON响应。鉴于我已经知道列名称,我从这个响应中创建了一个表:

#Flask App
@app.route('/process', methods=['POST', 'GET'])
def process():
    # ... queries database and returns value in list of dicts
    response = jsonify(db_result_dict)
    return response


//js
response = $.parseJSON(response);
$(function () {
    $.each(response, function (i, item) {
        $('<tr>').append(
        $('<td>').text(item.id),
        $('<td>').text(item.location),
        $('<td>').text(item.category)).appendTo('#my_table');       
    });
});


<!--html-->
<table id="my_table">
    <tr>
        <th>id</th>
        <th>location</th>
        <th>category</th>
    </tr>
</table>

没有Ajax,我曾经和Jinja做过类似的事情:

#Flask app
@app.route('/process', methods=['POST', 'GET'])
    def process():
        # ... queries database and returns value in list of dicts
        # ... get list of keys    
        return render_template('page.html', columns=list_of_keys, data=db_result_dict)


    <!--page.html-->
    <table id="my_table">
       <thead>
          {% for col in columns %}
          <td> {{ col }} </td>
          {% endfor %}
       </thead>
       {% for row in data %}
       <tr>
          {% for col in columns %}
          <td> {{row[col] }} </td>
          {% endfor %}
       </tr>
       {% endfor %}
    </table>

如果我事先不知道列名,我怎样才能以类似的方式从Ajax动态创建表?

1 个答案:

答案 0 :(得分:0)

我终于明白了:

简单地说,我将select max(case when v.Name = 'Size' then vo.VariantOptionName end) as Size, max(case when v.Name = 'Color' then vo.VariantOptionName end) as Color, max(case when v.Name = 'Material' then vo.VariantOptionName end) as Material, s.price, s.barcode from sku s join VariantOptionCombination voc on s.SkuID = voc.SkuID join VariantOption vo on vo.VariantOptionID = voc.VariantOptionID join Variant v on v.VariantID = vo.VariantID group by s.barcode, s.Price; 中的表格放到外部html文件中,并将所需的jinja模板添加到其中。然后在我的Flask应用程序中,我将render_template响应返回给jquery(其中包含我想要追加的HTML)。然后只需将响应中的HTML附加到要更新的所需div