POST请求后Jinja2模板无法显示响应数据问题求助
FastAPI + Jinja2 模板渲染问题:POST请求后页面不显示返回的recipe数据
使用FastAPI搭配Jinja2模板开发时,提交表单发送POST请求后,后端已生成recipe数据并返回包含该数据的TemplateResponse,通过浏览器开发者工具Network面板能看到响应中存在recipe内容,但页面模板却无法显示该数据。想请教这是什么原因,是否和前端的script.js有关?
相关代码
home.jinja模板
<section class="order-interface"> <div class="order-parameters"> <form method="POST" action="{{ url_for('generate_meal_recipe') }}" id="order-form"> <label for="cuisineType">Choose your preferred cuisine(s) if any:</label><br> <input type="checkbox" name="cuisineType" value="american"> 🇺🇸 American<br> <input type="checkbox" name="cuisineType" value="asian"> 🌏 Asian<br> <input type="checkbox" name="cuisineType" value="british"> 🇬🇧 British<br> <input type="checkbox" name="cuisineType" value="caribbean"> 🌴 Caribbean<br> <input type="checkbox" name="cuisineType" value="central europe"> 🇪🇺 Central Europe<br> <input type="checkbox" name="cuisineType" value="chinese"> 🇨🇳 Chinese<br> <input type="checkbox" name="cuisineType" value="eastern europe"> 🇪🇺 Eastern Europe<br> <input type="checkbox" name="cuisineType" value="french"> 🇫🇷 French<br> <input type="checkbox" name="cuisineType" value="indian"> 🇮🇳 Indian<br> <input type="checkbox" name="cuisineType" value="italian"> 🇮🇹 Italian<br> <input type="checkbox" name="cuisineType" value="japanese"> 🇯🇵 Japanese<br> <input type="checkbox" name="cuisineType" value="kosher"> 🕍 Kosher<br> <input type="checkbox" name="cuisineType" value="mediterranean"> 🌊 Mediterranean<br> <input type="checkbox" name="cuisineType" value="mexican"> 🇲🇽 Mexican<br> <input type="checkbox" name="cuisineType" value="middle eastern"> 🌍 Middle Eastern<br> <input type="checkbox" name="cuisineType" value="nordic"> ❄️ Nordic<br> <input type="checkbox" name="cuisineType" value="south american"> 🌎 South American<br> <input type="checkbox" name="cuisineType" value="south east asian"> 🌏 South East Asian<br> <input type="checkbox" name="cuisineType" value="world"> 🌍 World<br> <label for="mealType">Choose the type of meal:</label><br> <select name="mealType" id="mealType"> <option value="breakfast">Breakfast</option> <option value="brunch">Brunch</option> <option value="dinner">Dinner</option> <option value="snack">Snack</option> <option value="teatime">Teatime</option> </select> <label for="diet">Choose your diet if any:</label><br> <input type="checkbox" name="diet" value="balanced"> 🌿 Balanced<br> <input type="checkbox" name="diet" value="high-fiber"> 🌾 High Fiber<br> <input type="checkbox" name="diet" value="high-protein"> 🥩 High Protein<br> <input type="checkbox" name="diet" value="low-carb"> 🥦 Low Carb<br> <input type="checkbox" name="diet" value="low-fat"> 🍎 Low Fat<br> <input type="checkbox" name="diet" value="low-sodium"> 🧂 Low Sodium<br> <label for="health">Choose your health preferences if any:</label><br> <input type="checkbox" name="health" value="alcohol-cocktail"> 🍹 Alcohol Cocktail<br> <input type="checkbox" name="health" value="alcohol-free"> 🚱 Alcohol Free<br> <input type="checkbox" name="health" value="celery-free"> 🌱 Celery Free<br> <input type="checkbox" name="health" value="crustacean-free"> 🦀 Crustacean Free<br> <input type="checkbox" name="health" value="dairy-free"> 🥛 Dairy Free<br> <input type="checkbox" name="health" value="DASH"> DASH<br> <input type="checkbox" name="health" value="egg-free"> 🥚 Egg Free<br> <input type="checkbox" name="health" value="fish-free"> 🐟 Fish Free<br> <input type="checkbox" name="health" value="fodmap-free"> FODMAP Free<br> <input type="checkbox" name="health" value="gluten-free"> 🌾 Gluten Free<br> <input type="checkbox" name="health" value="immuno-supportive"> Immuno Supportive<br> <input type="checkbox" name="health" value="keto-friendly"> Keto Friendly<br> <input type="checkbox" name="health" value="kidney-friendly"> Kidney Friendly<br> <input type="checkbox" name="health" value="kosher"> 🕍 Kosher<br> <input type="checkbox" name="health" value="low-fat-abs"> Low Fat Abs<br> <input type="checkbox" name="health" value="low-potassium"> Low Potassium<br> <input type="checkbox" name="health" value="low-sugar"> Low Sugar<br> <input type="checkbox" name="health" value="lupine-free"> Lupine Free<br> <input type="checkbox" name="health" value="Mediterranean"> 🌊 Mediterranean<br> <input type="checkbox" name="health" value="mollusk-free"> Mollusk Free<br> <input type="checkbox" name="health" value="mustard-free"> Mustard Free<br> <input type="checkbox" name="health" value="no-oil-added"> No Oil Added<br> <input type="checkbox" name="health" value="paleo"> 🦴 Paleo<br> <input type="checkbox" name="health" value="peanut-free"> 🥜 Peanut Free<br> <input type="checkbox" name="health" value="pescatarian"> Pescatarian<br> <input type="checkbox" name="health" value="pork-free"> Pork Free<br> <input type="checkbox" name="health" value="red-meat-free"> Red Meat Free<br> <input type="checkbox" name="health" value="sesame-free"> Sesame Free<br> <input type="checkbox" name="health" value="shellfish-free"> Shellfish Free<br> <input type="checkbox" name="health" value="soy-free"> Soy Free<br> <input type="checkbox" name="health" value="sugar-conscious"> Sugar Conscious<br> <input type="checkbox" name="health" value="sulfite-free"> Sulfite Free<br> <input type="checkbox" name="health" value="tree-nut-free"> 🌰 Tree Nut Free<br> <input type="checkbox" name="health" value="vegan"> 🌱 Vegan<br> <input type="checkbox" name="health" value="vegetarian"> 🥕 Vegetarian<br> <input type="checkbox" name="health" value="wheat-free"> 🌾 Wheat Free<br> <input type="submit" value="Submit"> </form> </div> {% if recipe %} <div>{{recipe}}</div> {% endif %} </section>
script.js
document .getElementById("order-form") .addEventListener("submit", function (event) { event.preventDefault(); let q = document.getElementById("q").value; // Convert selected checkboxes to list // cuisineType let cuisineType_checkboxes = document.getElementsByName("cuisineType"); let cuisineType = Array.from(cuisineType_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // mealType let mealType = [document.getElementById("mealType").value]; // diet let diet_checkboxes = document.getElementsByName("diet"); let diet = Array.from(diet_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); // health let health_checkboxes = document.getElementsByName("health"); let health = Array.from(health_checkboxes) .filter((checkbox) => checkbox.checked) .map((checkbox) => checkbox.value); let form_data = { q: q, cuisineType: cuisineType, mealType: mealType, diet: diet, health: health, }; // Send the data to the server fetch("/", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify(form_data), }) .then((response) => response.text()) .then((data) => { console.log(data); document.getElementById("order-form").reset(); // Reset the form }) .catch((error) => console.error("Error:", error)); });
main.py
from fastapi import FastAPI, Request, Response from fastapi.staticfiles import StaticFiles from fastapi.templating import Jinja2Templates from pydantic import BaseModel from typing import List, Optional app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") templates = Jinja2Templates(directory="templates") class Order(BaseModel): """Order object.""" q: str cuisineType: Optional[List[str]] = [] mealType: Optional[List[str]] = [] diet: Optional[List[str]] = [] health: Optional[List[str]] = [] @app.get("/") async def home(request: Request) -> Response: """Home page.""" return templates.TemplateResponse("home.jinja", {"request": request}) @app.post("/") async def generate_meal_recipe(request: Request, order: Order) -> Response: """Retrieve generated meal recipe.""" # Logic recipe = "abc" return templates.TemplateResponse("home.jinja", context={"request": request, "recipe": recipe})
问题原因及解决办法
核心原因:异步请求未更新页面
你的script.js中使用了fetch发送异步POST请求,并且调用event.preventDefault()阻止了表单的默认提交行为。后端返回的带recipe的HTML页面只是被你用console.log(data)打印出来,但并没有替换当前页面的内容,所以页面还是初始加载的状态,自然不会显示recipe。
解决办法
有两种常见方案可选:
方案1:移除JS异步逻辑,使用表单默认提交
如果不需要无刷新页面的效果,可以直接删除整个script.js中的表单提交监听代码,让表单以默认方式提交。这样后端返回的TemplateResponse会直接替换当前页面,recipe数据就能正常渲染。
方案2:保留异步请求,手动更新页面内容
如果需要无刷新体验,需在fetch的回调中把返回的HTML插入到页面中。修改script.js中的then回调:
.then((data) => { // 替换整个order-interface区域的内容 document.querySelector('.order-interface').innerHTML = data; document.getElementById("order-form").reset(); })
额外问题:前端缺少q输入框
你的Order模型中q是必填字段,但home.jinja的表单里没有id="q"的输入元素,这会导致前端提交时q的值为undefined,后端解析会报错。需要在表单中添加对应的输入框:
<label for="q">Search keyword:</label> <input type="text" id="q" name="q">
内容的提问来源于stack exchange,提问作者aaronted
相关产品推荐
相关产品推荐

