简体   繁体   English

将 JSON 对象从 Flask 传递到 JavaScript

[英]Passing a JSON object from Flask to JavaScript

I'm having troubles getting a Flask/Python variable passed to Javascript.我在将 Flask/Python 变量传递给 Javascript 时遇到问题。

Basically, I'm importing from MySQL and have tried rendering the return in three different ways.基本上,我从 MySQL 导入并尝试以三种不同的方式呈现返回值。

  1. (43.8934276, -103.3690243), (47.052060, -91.639868), (45.1118, -95.0396) that is the output when my dict item has the following ran on it. (43.8934276, -103.3690243), (47.052060, -91.639868), (45.1118, -95.0396)这是我的 dict 项上运行以下内容时的输出。

new_list = [tuple(d.values()) for d in MySQL_Dict] output = ', '.join('(' + ', '.join(i) + ')' for i in new_list)

This method is no good, but I added it for detail, it's not in the right format at all.这个方法不行,我加了细节,格式不对。

  1. I pass the python dict directly to the template which looks like this我将 python 字典直接传递给看起来像这样的模板

({'lat': '43.8934276', 'lng': '-103.3690243'}, {'lat': '47.052060', 'lng': '-91.639868'}, {'lat': '45.1118', 'lng': '-95.0396'})

Then on the the template side I've tried the following JavaScript lines然后在模板方面我尝试了以下 JavaScript 行

 var other_coords = {{ MySQL_Dict|tojson }}; 
 var other_coords = {{ MySQL_Dict|tojson|safe }};
 var still_more = JSON.parse(other_coords);

None of which work, together or separately.这些都不起作用,一起或单独。

  1. I've also tried sending the dictionary from the view using json_out = json.dumps(My_Dict) which does not work either.我还尝试使用json_out = json.dumps(My_Dict)从视图发送字典,这也不起作用。

This is all with the goal of getting the lat, lng coords from the MySQL DB to the Google Maps API script.这一切都是为了将 lat、lng 坐标从 MySQL DB 获取到 Google Maps API 脚本。 The thing that is so confusing to me is that if I just paste the json.dump results from the view into the Google Maps script it works perfectly (after the quotes are removed) but if I use a variable it will not work for me.让我感到困惑的是,如果我只是将视图中的 json.dump 结果粘贴到 Google Maps 脚本中,它就可以完美地工作(在删除引号之后),但是如果我使用变量,它将对我不起作用。 Does anyone have suggestions?有人有建议吗?

It seems that the currently accepted answer (by @BrettJ) has a possible security flaw in it: if the object we pass to javascript has some string with a single quote inside, this single quote will not be escaped by json.dumps , thus allowing to inject arbitrary code into javascript. 似乎当前接受的答案(由@BrettJ)有一个可能的安全漏洞:如果我们传递给javascript的对象有一些带有单引号的字符串,这个单引号不会被json.dumps转义,因此允许将任意代码注入javascript。 It is better to use Flask's tojson() template filter, see the docs , as it makes proper escaping of all such characters (replace them with unicode codes). 最好使用Flask的tojson()模板过滤器,查看文档 ,因为它可以正确地转义所有这些字符(用unicode代码替换它们)。

Here is my solution: 这是我的解决方案:

view.py view.py

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def hello_world():
    user = {'firstname': "Mr.", 'lastname': "My Father's Son"}
    return render_template("index.html", user=user)

if __name__ == '__main__':
    app.run()

index.html 的index.html

<p>Hello, <span id="username"></span></p>
<script>
    var user = JSON.parse('{{ user | tojson | safe}}');
    document.getElementById('username').innerHTML = user.firstname + " " +
            user.lastname;
</script>

Generated JS looks like: 生成的JS看起来像:

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father\u0027s Son"}');

which is perfectly safe. 这是非常安全的。 For example, if we'd use json.dumps -powered solution, we'd get 例如,如果我们使用json.dumps解决方案,我们就会得到

var user = JSON.parse('{"firstname": "Mr.", "lastname": "My Father's Son"}');

which is syntactically incorrect (to say the least). 这在语法上是不正确的(至少可以说)。

The below simple example should show how to get a Javascript object from your dict: 下面的简单示例应该显示如何从您的dict获取Javascript对象:

views.py views.py

@app.route('/', methods=['GET','POST'])                                         
def index():                                                                    

    points = [{"lat": 43.8934276, "lng": -103.3690243},                         
              {"lat": 47.052060, "lng": -91.639868},                            
              {"lat": 45.1118, "lng": -95.0396}]                                

    return render_template("index.html", points=json.dumps(points)) 

index.html (some code removed for brevity) index.html (为简洁起见,删除了一些代码)

  function initMap() {                                                      

    var map = new google.maps.Map(document.getElementById('map'), {         
      center: new google.maps.LatLng(43.8934276, -103.3690243),             
      zoom: 4                                                               
    });                                                                     

    var points = JSON.parse('{{ points|safe }}');                           
    var marker;                                                             

    for (var i = 0; i < points.length; i++) {                               

        marker = new google.maps.Marker({                                   
          position: new google.maps.LatLng(points[i].lat, points[i].lng),   
          map: map                                                          
        });                                                                 

    }                                                                       
  }   

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM