python的字符串传递到JavaScript展示
时间: 2023-06-16 15:02:11 浏览: 129
可以使用 Flask 框架和 Jinja2 模板引擎来实现 Python 字符串传递到 JavaScript 展示的功能。具体步骤如下:
1. 在 Flask 应用中定义一个路由,以便接收请求并返回模板,代码如下:
```python
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
message = "Hello, world!"
return render_template("index.html", message=message)
```
2. 在模板(index.html)中使用 Jinja2 模板引擎将 Python 字符串传递到 JavaScript 中,代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Python to JavaScript</title>
</head>
<body>
<p id="message">{{ message }}</p>
<script>
var message = document.getElementById("message").textContent;
alert(message);
</script>
</body>
</html>
```
在模板中,使用 `{{ message }}` 将 Python 变量 message 的值传递到 HTML 中的 `p` 元素中。然后,在 JavaScript 中,使用 `document.getElementById("message").textContent` 获取该元素的文本内容,并将其存储在变量 `message` 中。最后,使用 `alert(message)` 显示该变量的值。
3. 运行 Flask 应用并访问网页,即可看到弹出窗口显示 Python 字符串的值。
```bash
$ flask run
```
在浏览器中访问 http://localhost:5000/,即可看到弹出窗口显示 "Hello, world!"。
阅读全文
相关推荐


















