JavaScript使用Jinja模板中呈现的数据引发SyntaxError

时间:2016-02-22 13:51:06

标签: javascript python flask

我正在尝试将数据作为JSON从Flask路由传递到呈现JavaScript的Jinja模板。我想使用JavaScript迭代数据。在渲染数据上调用SyntaxError: Unexpected token '&'. Expected a property name.时,浏览器会显示JSON.parse。如何在JavaScript中使用渲染的JSON数据?

var obj = JSON.parse({{ data }})
for (i in obj){
   document.write(obj[i].text + "<br />");
}
def get_nodes(node):
    d = {}
    if node == "Root":
        d["text"] = node
    else:
        d["text"] = node.name

    getchildren = get_children(node)
    if getchildren:
        d["nodes"] = [get_nodes(child) for child in getchildren]
    return d

tree = get_nodes("Root")
return render_template("folder.html", data=tree)

如果我只是将{{ data }}放在HTML部分中,我看到的内容看起来是正确的。

{'text': 'Root', 'nodes': [{'text': u'Prosjekt3'}, {'text': u'Prosjekt4', 'nodes': [{'text': u'mappe8'}]}]}

3 个答案:

答案 0 :(得分:12)

Flask的Jinja环境会自动转义HTML模板中呈现的数据。这是为了避免在开发人员尝试呈现不受信任的用户输入时出现安全问题。

由于您传递的Python对象被视为JSON,因此Flask提供 public ControlMachineII() { InitializeComponent(); DataContextChanged += new DependencyPropertyChangedEventHandler(ControlMachineII_DataContextChanged); } private void ControlMachineII_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { string compname = (this.DataContext as Model.Model.ControleData).ComputerName; Console.WriteLine("DataContext initialized computername :" +compname); } 过滤器,该过滤器会自动将数据转储到JSON并将其标记为安全。

tojson
return render_template('tree.html', tree=tree)

当您查看HTML中呈现的数据时,它看起来是正确的,因为浏览器将转义的符号显示为真实符号(尽管在这种情况下您会看到Python字典的字符串表示形式,而不是JSON,所以还有一些问题,如var tree = {{ tree|tojson }}; 标记。)

Flask的早期版本没有标记转储数据的安全性,因此您可能会遇到u这样的示例,而这些示例已不再需要了。

如果您没有呈现JSON(或者您已经将JSON转储到字符串中),您可以告诉Jinja使用{{ tree|tojson|safe }}过滤器可以安全地呈现数据而无需转义。

safe
# already dumped to json, so tojson would double-encode it
return render_template('tree.html', tree=json.dumps(tree))

您还可以在呈现之前将字符串包装在var tree = {{ tree|safe }}; 中,它等同于Markup过滤器。

safe
# already dumped and marked safe
return render_template('tree.html', tree=Markup(json.dumps(tree)))

如果你没有将这些数据传递给JavaScript,而是在Jinja中使用它,那么你就不需要JSON了。传递实际的Python数据,不要在其上调用var tree = {{ tree }}; ,并像使用模板中的任何其他数据一样使用它。

tojson
return render_template('tree.html', tree=tree)

答案 1 :(得分:-1)

我可以使用以下代码示例对其进行存档。

def Newton(f,x0,eps,N):
    """here I implement Newton's method"""
    #(...) iterations go here (...)
    return x
def f(x): function for testing
   return ...

quit() # Unfortunately this raises a Traceback, at least when the file is "Run" 
# on pythonanywhere.com. I'd like to avoid this. I would simply like everything
# to be ignored after this point, let's say "for convenience", to simplify.
# I'd like to know whether this is possible, in the given configuration.

def f(x):# this is another function for testing
   return [something else]
[...] # another formula to try. This is just a snippet and might not compile.
def Newton(...):# the old version. Not yet trashed because maybe needed.
      # Would have to rename this if the whole file is read by the compiler.

# Below follow more routines which are part of the final version of this file, 
# but I don't want to compile all of them each time, while I fiddle around with
# the latest addition, for now put the beginning of the file.
# OTOH I would like to have that code in the same file for easier copy-paste in
# case I need some parts of it while developing the new stuff at top of file.

答案 2 :(得分:-3)

问题是您的服务器不返回JSON,而是呈现HTML,它会使&amp;符号

而不是使用

return render_template("folder.html", data=tree)

return flask.jsonify(**tree)