我是一个使用 Flask 框架(通常是客户端-服务器)的真正新手,所以请耐心等待。我有一个基本的 HTML 模板文件,其中包含一些 Flask(使用 {% ... %} 表示法)从 python 文件传递 JSON 对象。现在,作为一个简单的健全性检查,它输出 motifs
的内容。 (数组的数组)作为无序列表 ( <li>
) 中的单独行 ( <ul>
)。
我希望它做的是使用 motifs
JavaScript 脚本中的数组数组作为我正在尝试执行的可视化的数据。我尝试将 Flask 脚本混合到 JavaScript <script>
迭代出 JavaScript 数组的标签,但收到一个错误,该脚本标签不喜欢 Flask 表示法( Uncaught SyntaxError: Unexpected token }
。那么如何让 Flask 脚本将数组用于 JavaScript 脚本呢?我意识到我可能误解了这里的一些事情(也许是 JSON 的本质?)。如果有任何正确方向的插入,我将不胜感激。谢谢!
下面我将我的 html 模板与创建无序列表的 Flask 脚本一起包含在内,我还在 <script>
中包含了使用 Flask 脚本的失败尝试。标签。那么如何在 JavaScript 中成功访问数组 (JSON)?
index.html(模板文件 - 为清楚起见,此处进行了简化):
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<p>Here are some motifs:</p>
<ul>
{% for motif in motifs %}
<li>{{motif}}</li>
{% endfor %}
</ul>
<script>one of a few js scripts</script>
</body>
</html>
上述文件的输出如下所示(缺少未复制的要点):
以下是一些主题:
{'基因1':1,'基因2':1,'基因3':7,'基因4':7,'基因5':1}
{'基因1':7,'基因2':4,'基因3':10,'基因4':5,'基因5':2}
{'基因1':7,'基因2':1,'基因3':8,'基因4':5,'基因5':8}
{'基因1':2,'基因2':4,'基因3':6,'基因4':1,'基因5':9}
{'基因1':3,'基因2':8,'基因3':2,'基因4':7,'基因5':8}
{'基因1':1,'基因2':5,'基因3':1,'基因4':9,'基因5':5}
{'基因1':3,'基因2':5,'基因3':6,'基因4':10,'基因5':9}
{'基因1':2,'基因2':10,'基因3':7,'基因4':5,'基因5':10}
{'基因1':5,'基因2':5,'基因3':10,'基因4':10,'基因5':5}
{'基因1':10,'基因2':4,'基因3':4,'基因4':6,'基因5':4}
下面是我在 <script>
中访问失败的尝试Flask 传递的数组(JSON 对象):
<script>
var motifValuesArray = [];
var index = 0; // an iterator to assign indexes in the javascript array
{% for motif in motifs %}
motifValuesArray[index] = {motif};
console.log(motifValuesArray[index]);
{% endfor %}
</script>
最佳答案
所以你的<script>
的原因尝试failed is because you're attempting to run jinja2 code (默认情况下 Flask 附带的模板引擎)在 Web 浏览器中。 The web browser doesn't have a python interpreter let alone a templating engine that is built on top of python.
话虽如此,您可以通过多种方式将 JSON 数组从 Flask 获取到客户端。 Probably the simplest way is to pass the array as straight HTML and parse the html.但这不是很流畅,如果您的数组变得非常大,那么速度可能会非常慢。
Just to be thorough, this SO answer goes through how to do things straight from jinja2.
对于我的示例,我将创建一个在页面加载时调用的 JavaScript 函数。该 javascript 函数对 Flask 应用程序进行 ajax 调用,接收 JSON 格式的数组,最后解析对象以返回数组。
Javascript
$(document).ready(function() {
var request = $.ajax({
type: "POST",
url: "/example_array/",
data: {"name":""}, // if you wanted to specifiy what list then pass an actual name
dataType: "html"
});
request.done(function(JSON_array) {
array_data = JSON.parse(JSON_array)["array"]
//from here you have your array to play with
});
});
flask 文件
from flask import jsonify
@app.route("/example_array/")
def example():
list = get_list() # however you get your list data, put it here
return jsonify(array=list)
@app.route("/")
def index():
return render_template("home_page.html")
关于javascript - 如何在前端JavaScript中访问Python(Flask)传递的数组(JSON)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18835414/