【问题标题】:How to send the value of a Python variable to JavaScript in HTML如何将 Python 变量的值发送到 HTML 中的 JavaScript
【发布时间】:2018-01-04 16:19:23
【问题描述】:

我正在使用 Google App Engine 在网页上显示 Google 地图。

我想把数据库中的经纬度带入到地图上显示。为此,我需要将导入的纬度和经度传递给 HTML 中的 JavaScript。我尝试了几种方法,但它没有用。 (例如{{variable}} 没用。)

如何最好地调试或以其他方式继续此操作?

class Map(webapp2.RequestHandler):

    db = connect_to_cloudsql()
    cursor = db.cursor()
    cursor.execute("""select latitude,longitude from User;""")

    data=cursor.fetchone() 
    lat=data[0]
    lng=data[1]

    formstring = """
    <!DOCTYPE html> 
    <html lang="ko-KR">
    <head>
    <meta charset="utf-8"/>
        <meta name="google-site-verification" content="9EqLgIzCmwFo7XAcSe4sBNZ_t0gULadyeF9BCO0DY3k"/>
    </head>
    <body class>
    <style>
     #map {
        width: 80%;
        height: 400px;
        background-color: grey;
      }
    </style>
    <div style="position:relative;width:1080px;margin:0 auto;z-index:11">
    <div class="container" role="main">
    <div id="map"></div>
    <br><br>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=mykey&callback=initMap">
    </script>
     <script>
      function initMap() {

        var uluru = {lat: {lat} , lng: {lng} };
        var map = new google.maps.Map(document.getElementById('map'), {
          zoom: 4,
          center: uluru
        });
        var marker = new google.maps.Marker({
          position: uluru,
          map: map
        });
      }
    </script>

    </div>
    </div>
    </body>
    </html>
        """

【问题讨论】:

  • 你形成 html 代码的方式很糟糕,但如果是这样 - 打破 html 代码字符串,将 lat-lng 值附加到字符串并形成 html 代码。
  • 不要在 Python 文件中编写 HTML。 GAE 支持 Jinja2,你应该使用它。
  • 如果您仍然坚持以这种方式形成字符串,请确保将所有 { 替换为 {{} 替换为 }}{lat} 和 {lng 除外},然后只需在 formstring 上拨打 .format(lat=lat, lng=lng}
  • """{{lat:{0} lng:{1}}}""".format(lat, lng)

标签: javascript python html google-app-engine


【解决方案1】:

看看string formatters。随着您的 Web 应用程序的发展,您可能希望切换到使用模板,因为它们更健壮。 Webapp2 provides support 代表Jinja2 templates,它们被广泛使用,从长远来看将使您的生活更轻松。

但在短期内,使用字符串格式化程序:

formstring = """
<!DOCTYPE html> 
...

    var uluru = {lat: %f , lng: %f };
    var map = new google.maps.Map(document.getElementById('map'), {
...
""" % (lat, lng)  # assuming lat/lng are floats, use %s instead of %f for strings

或者,使用“新方式”:

formstring = """<html.......{lat: {:f}, lng: {:f}...""".format(lat, lng)

再次查看string formatters

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    相关资源
    最近更新 更多