来自服务器json对象的数据表

时间:2018-05-20 01:06:55

标签: javascript jquery ajax datatables

我将表单数据作为ajax post请求提交给后端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)

1 个答案:

答案 0 :(得分:1)

使用ajax调用作为数据源

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

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

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