首页 > 解决方案 > JS通过烧瓶{{变量}}格式访问python变量不起作用

问题描述

Python:

import json
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
encoded_posts = json.dumps(posts)

javascript:

let obj = {{ encoded_posts }};

JS错误登录控制台:

Uncaught SyntaxError: Unexpected token ';'

这是根据控制台的页面。它似乎正在失去(?){{encoded_posts}}

<!DOCTYPE html>
<html>
  <head>

      <title>Flask Blog - About</title>

  </head>
  <body>
    <h1>About page!</h1>
    <script>
      let text = document.getElementsByTagName('h1')[0];
      text.addEventListener('click',function(){
        text.style.color = 'red';
      });

      let obj = ;
      let jsonPosts = JSON.parse();
      console.log(jsonPosts);

    </script>
  </body>
</html>

发生了什么?

标签: javascriptpythonflask

解决方案


您是否尝试过这样做:

let obj = JSON.parse('{{ encoded_posts }}');

推荐阅读