Javascript 如何将flask返回值作为变量传递给java脚本函数

Javascript 如何将flask返回值作为变量传递给java脚本函数,javascript,python,html,flask,Javascript,Python,Html,Flask,我在flask中编写了一个应用程序,它将值列表返回到html页面,并将值传递给html中的一个变量以调用java脚本函数 我试图执行以下代码,但它显示了一条错误消息: jinja2.exceptions.UndefinedError jinja2.exceptions.UndefinedError: 'jsonfile' is undefined File "C:\NGConf-Explorer\myproject\templates\index.html", line 27, in top

我在flask中编写了一个应用程序,它将值列表返回到html页面,并将值传递给html中的一个变量以调用java脚本函数

我试图执行以下代码,但它显示了一条错误消息:

jinja2.exceptions.UndefinedError
jinja2.exceptions.UndefinedError: 'jsonfile' is undefined 

File "C:\NGConf-Explorer\myproject\templates\index.html", line 27, in top-level template code
JSONTREEVIEWER.processJSONTree('{{ url_for('static', filename=[jsonfile[0]])}}','0');
File "C:\NGConf-Explorer\myproject\venv\lib\site-packages\jinja2\environment.py", line 411, in getitem
return obj[argument]
jinja2.exceptions.UndefinedError: 'jsonfile' is undefined
烧瓶代码:

@app.route('/')
def home():
    if not session.get('logged_in'):
        return render_template('login.html')
    else:
        # Open a file
        #path= r"C:\NGConf-Explorer\myproject\yang\\"
        #dirs = os.listdir(path)
        filename = []
        dirs = ['Pyang_output.json2', 'Pyang_output.json3']
        for file in dirs:
            #filename.append(file).as_uri()
            #print(filename)
            filename.append(file)
        return render_template('index.html',filename=filename)
HTML代码:

<script type="text/javascript">
$(function(){
    JSONTREEVIEWER.init();
    file = {{filename|tojson}}; 
    var i;
     for (i = 0; i < file.length; i++) { 
             JSONTREEVIEWER.processJSONTree('{{ url_for('static', 
              filename=file[0])}}','0');
      } 

$(函数(){
JSONTREEVIEWER.init();
file={{filename | tojson}};
var i;
对于(i=0;i
我怀疑您混淆了模板扩展时间和JavaScript执行时间

$(function(){
    JSONTREEVIEWER.init();
    jsonfile = {{filename|tojson}};
    console.log(jsonfile[0])
    JSONTREEVIEWER.processJSONTree('{{ url_for('static', filename=jsonfile[0])}}','0');
模板提供了
filename
(这是一个名称列表),但不提供
jsonfile
,这是一个名称,一旦扩展的模板交付到浏览器,JavaScript执行此片段,JavaScript就会看到该名称

但在此之前,Jinja2尝试扩展
url\u for()
,这要求为其提供
jsonfile
绑定

JSONTREEVIEWER.processJSONTree('{{ url_for('static', filename=filename[0])}}','0');

谢谢,如果我将文件名变量作为文件名[0]传递,它就工作了。但是如果使用下面的代码,它就不工作了。文件={{filename | tojson}};变量I;for(I=0;Iconsole.log()JS中的调用应该会告诉您发生了什么。您需要打开浏览器开发工具以获得控制台。如何操作取决于您使用的浏览器。