将Javascript数组传递给Flask

Alo*_*sai 5 javascript python flask

我在flask中有一个名为array的函数,它接受一个列表并打印出列表中的项目:

def array(list):
    string = ""
    for x in list:
        string+= x
    return string
Run Code Online (Sandbox Code Playgroud)

在客户端,我想将名为str的javascript数组传入此数组.我该怎么办?这就是我现在所拥有的,但Flask并未阅读添加的变量.有任何想法吗?

for (var i = 0; i < response.data.length; i++) {
            console.log(i);

            // str = str + "<br/><b>Pic</b> : <img src='"+ response.data[i].picture +"'/>";

            str[i] = response.data[i].picture;
        }
        window.location = "{{ url_for('array', str=list ) }}";
Run Code Online (Sandbox Code Playgroud)

Ale*_*sen 9

Flask有一个名为request的内置对象.在请求中有一个名为args的multidict.

您可以使用它request.args.get('key')来检索查询字符串的值.

from flask import request

@app.route('/example')
def example():
    # here we want to get the value of the key (i.e. ?key=value)
    value = request.args.get('key')
Run Code Online (Sandbox Code Playgroud)

当然这需要获取请求(如果您使用帖子然后使用request.form).在javascript方面,您可以使用纯javascript或jquery发出get请求. 我将在我的例子中使用jquery.

$.get(
    url="example",
    data={key:value}, 
    success=function(data) {
       alert('page content: ' + data);
    }
);
Run Code Online (Sandbox Code Playgroud)

这是您将数据从客户端传递到烧瓶中的方法.jquery代码的函数部分是如何将数据从flask传递给jquery.例如,假设您有一个名为/ example的视图,并且从jquery端传入一个键值对"list_name":"example_name"

from flask import jsonify
def array(list):
    string = ""
    for x in list:
        string+= x
    return string

@app.route("/example")
def example():
    list_name = request.args.get("list_name")
    list = get_list(list_name) #I don't know where you're getting your data from, humor me.
    array(list)
    return jsonify("list"=list) 
Run Code Online (Sandbox Code Playgroud)

你会说,在jquery的成功函数中

  success=function(data) {
       parsed_data = JSON.parse(data)
       alert('page content: ' + parsed_data);
    }
Run Code Online (Sandbox Code Playgroud)

请注意,出于安全原因,flask不允许在json响应中使用顶级列表.