我有一个小的Python脚本,应该将字符串发送到我的HTML文件中的javascript,以便在页面上呈现。但是,脚本没有从Python文件接收发送给它的数据。我的代码如下:
simple.html:
<html>
<body>
<h1>Hello</h1>
<p1 id="demo"></p1>
<script>
var s = {{to_display}};
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
main.py:
from bottle import Bottle, template
app = Bottle()
@app.route('/')
def index():
data = {"to_display":"HI, how are you"}
return template("simple.html", data)
if __name__ == '__main__':
app.run()
我希望页面看起来像这样:
Hello
HI, how are you
不幸的是,它只显示:
Hello
有谁知道如何纠正这个问题?
答案 0 :(得分:1)
这里的问题是模板没有呈现有效的javascript。
>>> from bottle import template
>>> data = {'to_display': 'HI, how are you'}
>>> rendered = template('/home/kev/tmp/test.html', data)
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = HI, how are you;
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
在浏览器中加载此html会引发语法错误(在Firefox 52.3.0上测试):
SyntaxError: missing ; before statement
问题在于s
标记中未引用<script>
的定义。修正版:
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "{{ to_display }}";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>
渲染到此标记,该标记在浏览器中按预期工作:
>>> print rendered
<html>
<body>
<p1 id="demo"></p1>
<script>
var s = "HI, how are you";
var x = document.getElementById("demo");
x.innerHTML = s;
</script>
</body>
</html>