首页 > 解决方案 > 来自服务器 json 对象的数据表

问题描述

我将表单数据作为 ajax 发布请求提交给后端 Flask 应用程序。后端进程使用数据查询数据库,然后将 json 对象返回给 Ajax。如何从此 json 对象构造数据表?

我的 Ajax 发布请求:

$(document).ready(function() {
    $("#submit").click(function(event) {
        $.ajax({
            type: 'POST',
            url: '/process',
            data: $('#myform').serialize(),
            success: function(response) {
                //response looks like this: 
                //[{"country": "USA", "code": "1007-01" },{"country": "UK", "code": "1100-04" }]

            }
        });
        event.preventDefault();
    });
});

我的烧瓶应用程序

@app.route('/process', methods=["POST"])
def process():
    if request.method == 'POST':
       country = request.form['id'].encode("utf-8")
       #query database and store result in dict
       result = query_database(country)
       return jsonify(result)

标签: javascriptjqueryajaxdatatables

解决方案


使用 ajax 调用作为数据源初始化数据表

let datatable = $('#my-table').DataTable({
    ajax: {
        url: '/process',
        method: 'POST',
        data: {
            $('#myform').serialize()
        } 
    }
});

现在你只需要像这样格式化你的回复

{ 
    data:[/*your Data*/]
}

推荐阅读