gpt4 book ai didi

javascript - 如何将 Python 变量的值发送到 HTML 中的 JavaScript

转载 作者:行者123 更新时间:2023-11-28 04:21:41 26 4
gpt4 key购买 nike

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

我想将数据库中的纬度和经度带入并显示在 map 上。为此,我需要将导入的纬度和经度传递给 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>
"""

最佳答案

看看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 .

关于javascript - 如何将 Python 变量的值发送到 HTML 中的 JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45376148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com