【问题标题】:Why does Flask is receiving this variable as unicode but not as array?为什么 Flask 将这个变量作为 unicode 而不是作为数组接收?
【发布时间】:2019-10-20 07:33:06
【问题描述】:

我尝试使用 Jquery 通过 Post 方法发送一个数组。

function post_to_url(path, params, method) {
    method = method || "post"; // Set method to post by default, if not specified.

    // The rest of this code assumes you are not using a library.
    // It can be made less wordy if you use one.
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

var url = "{{url_for('page')}}";
post_to_url(url,{'data':arrayObj}, "post");

直到这里,当我使用console.log($.type(arrayObj)) 时,它返回给我一个数组。

@mod.route('/page',methods=["POST","GET"])
def page():
 if request.method=="POST":
  import pdb; pdb.set_trace()
  d = request.form['data']
  return render_template('testing/page.html',data=d)
 return render_template('testing/page.html')

使用 PDB,type(d) 变量返回一个 unicode。为什么?

【问题讨论】:

    标签: python jquery arrays post flask


    【解决方案1】:

    params 有一个键。 for循环执行一次,这一行:

    hiddenField.setAttribute("value", params[key]);
    

    …正在将隐藏字段值设置为序列化为字符串的数组。

    如果您知道所有的键都是数组对象,那么只需遍历值并插入多个输入元素:

    for (let key in params) {
        if (params.hasOwnProperty(key)) {
            let values = params[key];
            for (let value of values) {
                var hiddenField = document.createElement("input");
                hiddenField.setAttribute("type", "hidden");
                hiddenField.setAttribute("name", key);
                hiddenField.setAttribute("value", value);
                form.appendChild(hiddenField);
            }
        }
    }
    

    如果您不知道所有键都是数组,则可以更改后端代码以逗号分隔传入值。请注意,对于任何字面上包含 , 的值,这将中断。

    @mod.route('/page',methods=["POST","GET"])
    def page():
     if request.method=="POST":
      d = request.form['data']
      d_array = d.split(',')
      return render_template('testing/page.html',data=d_array)
     return render_template('testing/page.html')
    

    【讨论】:

    • Printing document.body.appendChild(form); 它正在创建一个隐藏的输入并将所有数组值存储在 value 字段中,例如 <input type="hidden" name="data" value="1,234,567,adsa,sadasf,23432,32432">
    • 没错。如果您想在 Flask 端创建一个数组,则必须使用 str.split 之类的东西解析单数输入,或者您的前端脚本需要为数组中的每个 n 项创建 n 隐藏输入。
    • 你能告诉我吗?我正在尝试,但没有成功!
    • 更新为在前端显示循环或在后端拆分。
    • 奇怪,它只是返回第一个位置,当我打印 form.appendChild 时,只返回一个值
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多