如何使用Flask处理从jquery数据表发送的服务器端参数? [英] How to process server side parameter sent from jquery datatables using Flask?
问题描述
启用服务器端处理后,在处理jquery数据表1.10发送的参数时遇到一些问题。我像这样在javascript端初始化了数据表:
I am having some issues in processing the parameters sent by jquery datatables 1.10 when server side processing is enabled. I initialized the datatable in the javascript side like this:
var table = $('#mytable').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
'url': url,
'type': 'POST'
},
"columns": data
} );
并使用以下命令在基于Flask的服务器中接收POST请求:
And receive the POST request in the Flask based server using this:
@app.route('/data/<data_key>', methods=['POST'])
def get_data(data_key):
print request.form
# do some processing here in order to filter data
# ...
return Response(json.dumps(data), status=200, mimetype='application/json')
为了过滤数据,我试图在request.form内部查找,但结果很奇怪,并且不能轻松地转换为对象数组。我得到这样的东西:
In order to filter the data I tried to look inside request.form but the result is weird and can't be transformed easily to an array of objects. I get somthing like this:
ImmutableMultiDict(
[
('columns[0][data]', u'ReportDate'),
('draw', u'1'),
('columns[1][name]', u''),
('columns[1][data]', u'FundName'),
('columns[0][orderable]', u'true'),
('columns[1][searchable]', u'true'),
('columns[1][orderable]', u'true'),
('order[0][column]', u'0'),
('columns[0][name]', u''),
('order[0][dir]', u'asc'),
('search[value]', u''),
('columns[1][search][regex]', u'false'),
('columns[0][search][value]', u''),
('search[regex]', u'false'),
('columns[1][search][value]', u''),
('columns[0][search][regex]', u'false'),
('start', u'0'),
('length', u'10'),
('columns[0][searchable]', u'true')
]
)
在他们说的jquery数据表文档:
In the jquery datatables documentation they say:
发送到服务器的order [i]和column [i]参数是信息数组:
The order[i] and columns[i] parameters that are sent to the server are arrays of information:
ord er [i]-是一个数组,定义要对多少列进行排序-即,如果数组长度为1,则将执行单列排序,否则将执行多列排序。
order[i] - is an array defining how many columns are being ordered upon - i.e. if the array length is 1, then a single column sort is being performed, otherwise a multi-column sort is being performed.
columns [i]-定义表中所有列的数组。
columns[i] - an array defining all columns in the table.
在两种情况下,i都是一个整数,将更改以指示该数组的值。在大多数现代的服务器端脚本环境中,这些数据将以数组的形式自动提供给您。
In both cases, i is an integer which will change to indicate the array value. In most modern server-side scripting environments this data will automatically be available to you as an array.
但是,Flask将此数据作为简单的字典提供,有没有一种方法可以轻松地将其转换为对象数组?
However, Flask provide this data as a simple dictionary, is there a way to transform it to an array of objects easily?
推荐答案
获取DataTable发送json
Get DataTable to send json
ajax: {
url: "/api/data_table",
type: "POST",
data: function ( args ) {
return { "args": JSON.stringify( args ) };
}
},
在烧瓶中,解析json
In flask, parse the json
args = json.loads(request.values.get("args"))
columns = args.get("columns")
这篇关于如何使用Flask处理从jquery数据表发送的服务器端参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!