You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flask模板渲染后JavaScript未执行问题求助

Flask渲染子模板后内嵌JavaScript无法执行

问题描述

主路由/返回index.html一切正常,点击页面按钮跳转至/edit路由,该路由业务逻辑执行完成后返回successful_save_alert.html模板,但模板内的JavaScript代码完全未执行。调试确认模板已被渲染,但Chrome的Sources面板中找不到该模板对应的文件。

相关代码

Flask路由

@app.route("/", methods=["GET", "POST"])
def index():
    # 业务逻辑代码
    return render_template("index.html")

@app.route("/edit", methods=["GET", "POST"])
def edit():
    # 业务逻辑代码
    return render_template("successful_save_alert.html")

模板文件

successful_save_alert.html(继承自index.html):

{% extends "index.html" %}
{% block script %}
<script>
    alert("保存成功!");
    console.log("alert触发");
</script>
{% endblock %}

index.html:

<!DOCTYPE html>
<html lang="en">
    <head>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
        <link href="/static/styles.css" rel="stylesheet">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta charset="UTF-8">
        <title>Database</title>
    </head>
    <body>
        <!-- 页面HTML内容 -->
        {% block script %}{% endblock %}
        <script src="static/edit.js"></script>
    </body>
</html>

Flask配置

app = Flask(__name__)
# 开启模板自动重载
app.config["TEMPLATES_AUTO_RELOAD"] = True

@app.after_request
def after_request(response):
    """禁止响应缓存"""
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

项目文件结构

├── app.py
├── database.db
├── static
│   ├── edit.js
│   └── styles.css
└── templates
    ├── index.html
    └── successful_save_alert.html

已尝试的无效方案

  • 调试确认模板已成功渲染
  • 检查Chrome Sources面板未发现目标文件
  • 验证项目文件结构无误
  • 新增独立路由直接渲染该模板,问题依旧
  • 尝试将脚本改为静态文件引入,无效
  • 移除所有Flask缓存配置,无效

需求

实现从/edit路由渲染successful_save_alert.html,并确保其中的JavaScript代码正常执行。


解决方案

1. 修正静态资源路径

index.html中引入edit.js的路径为相对路径static/edit.js,当路由为/edit时,浏览器会尝试请求/edit/static/edit.js,导致资源加载失败,可能阻塞后续脚本执行。改为绝对路径:

<script src="/static/edit.js"></script>

2. 检查模板渲染后的实际输出

在edit路由中打印渲染后的HTML,确认脚本标签是否正确嵌入:

def edit():
    # 业务逻辑代码
    html = render_template("successful_save_alert.html")
    print(html)  # 查看输出是否包含完整的<script>标签
    return html

如果输出中没有脚本,检查模板继承的block是否匹配,确保子模板的script块正确覆盖父模板的对应块。

3. 改用重定向+Flash消息(推荐方案)

这种场景更适合用重定向配合Flash消息,避免直接渲染子模板的问题:

  • 修改路由代码:
from flask import flash, redirect, url_for

@app.route("/edit", methods=["GET", "POST"])
def edit():
    # 业务逻辑代码
    flash("保存成功!")
    return redirect(url_for("index"))
  • 在index.html中添加Flash消息处理:
{% with messages = get_flashed_messages() %}
  {% if messages %}
    {% for msg in messages %}
      <script>alert("{{ msg }}");</script>
    {% endfor %}
  {% endif %}
{% endwith %}

4. 强制清除浏览器缓存

按Ctrl+Shift+R(Windows/Linux)或Cmd+Shift+R(Mac)强制刷新页面,清除浏览器缓存的旧资源。


内容的提问来源于stack exchange,提问作者Jack Kirby

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 09:51:28