使用 jquery 和 Flask 发送数组数据 [英] Sending array data with jquery and flask

查看:11
本文介绍了使用 jquery 和 Flask 发送数组数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据从 html 页面发送回我的 Python 应用程序:

I need to send data from a html page back into my Python application:

$.post("/test", {x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}, function(dat) {console.log(dat);});

在服务器上:

@app.route('/test', methods=['POST'])
def test():
    print request.form.keys()
    print dir(request.form)
    print request.form["x[]"]
    return jsonify({"Mean": 10.0})

令我惊讶的是,这些键是

Much to my surprise the keys are

['y[]', 'x[]']

print request.form["x[]"] 

结果为 1.

这样做的正确方法是什么?

What's the correct way to do this?

推荐答案

当发送包含数组或对象值的 POST 数据时,jQuery 遵循 PHP 为字段名称添加括号的约定.它不是网络标准,但由于 PHP 开箱即用地支持它,因此它很受欢迎.

When sending POST data containing values that are arrays or objects, jQuery follows a PHP convention of adding brackets to the field names. It's not a web standard, but because PHP supports it out of the box it is popular.

因此,正如您所发现的,在 Flask 端处理带有列表的 POST 数据的正确方法确实是将方括号附加到字段名称.您可以使用 检索列表的所有MultiDict.getlist():

As a result, the correct way of handling POST data with lists on the Flask side is indeed to append square brackets to the field names, as you discovered. You can retrieve all values of the list using MultiDict.getlist():

request.form.getlist("x[]")

(request.form 是一个 MultiDict 对象).这返回字符串,而不是数字.如果您知道值是数字,您可以告诉 getlist() 方法为您转换它们:

(request.form is a MultiDict object). This returns strings, not numbers. If you know the values to be numbers, you can tell the getlist() method to convert them for you:

request.form.getlist("x[]", type=float)

如果您不想应用额外的括号,请不要使用数组作为值,或者将您的数据编码为 JSON.不过,您必须使用 jQuery.ajax() 代替:

If you don't want the additional brackets to be applied, don't use arrays as values, or encode your data to JSON instead. You'll have to use jQuery.ajax() instead though:

$.ajax({
    url: "/test",
    type: "POST",
    data: JSON.stringify({x: [1.0,2.0,3.0], y: [2.0, 3.0, 1.0]}),
    contentType: "application/json; charset=utf-8",
    success: function(dat) { console.log(dat); }
});

在服务器端,使用 request.get_json() 解析发布的数据:

and on the server side, use request.get_json() to parse the posted data:

data = request.get_json()
x = data['x']

这也负责处理数据类型转换;您将浮点数作为 JSON 发布,Flask 将在 Python 端再次将它们解码为浮点数.

This also takes care of handling the datatype conversions; you posted floating point numbers as JSON, and Flask will decode those back to float values again on the Python side.

这篇关于使用 jquery 和 Flask 发送数组数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆