将 Javascript 数组传递给 Flask
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18796921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing Javascript Array to Flask
提问by Aloke Desai
I have a function in flask called array that takes in a list and prints out the items in the list:
我在烧瓶中有一个名为 array 的函数,它接收一个列表并打印出列表中的项目:
def array(list):
string = ""
for x in list:
string+= x
return string
On the client side, I want to pass in a javascript array named str into this array. How would I do that? Here's what I have right now, but Flask isn't reading the added variable. Any ideas?
在客户端,我想将名为 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 ) }}";
回答by AlexLordThorsen
Flask has a built in object called request. In request there is a multidict called args.
Flask 有一个名为 request 的内置对象。在请求中有一个称为 args 的 multidict。
You can use request.args.get('key')
to retrieve the value of a query string.
您可以使用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')
Of course this requires a get request (if you use a postthen use request.form
). On the javascript side you can make a get request using pure javascript or jquery.I'm going to use jquery in my example.
当然,这需要一个 get 请求(如果您使用 post则使用request.form
)。在 javascript 方面,您可以使用纯 javascript 或 jquery 发出获取请求。我将在我的示例中使用 jquery。
$.get(
url="example",
data={key:value},
success=function(data) {
alert('page content: ' + data);
}
);
This is how you pass data from the client into flask. The function portion of the jquery code is how you pass data from flask to jquery. Let's say for example you have a view called /example and from the jquery side you pass in a key value pair of "list_name":"example_name"
这就是您将数据从客户端传递到烧瓶的方式。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)
and in the success function in jquery you'd say
在 jquery 的成功函数中你会说
success=function(data) {
parsed_data = JSON.parse(data)
alert('page content: ' + parsed_data);
}
Note that flask does not allow for top level lists in json response for security reasons.