首页 > 解决方案 > fastapi、html 和表单。如何不加载新页面?

问题描述

我做了一个小演示来展示我要解决的问题。

应用程序.py

from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from pathlib import Path

app = FastAPI()
BASE_PATH = Path(__file__).resolve().parent
templates = Jinja2Templates(directory=str(BASE_PATH / "templates"))
g_word = ''

@app.get('/word', response_class=HTMLResponse)
def word(request: Request):
    return templates.TemplateResponse('word.html', {'request': request, 'word': g_word})

@app.post("/submit")
def submit(request: Request, word: str = Form(...)):
    global g_word
    g_word = word
    print (g_word)

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8001, log_level="debug")

word.html

<!DOCTYPE html>
<html>
<head>
<title>Word page</title>
</head>
<body>
<form action="/submit" method="post">
  <label for="word">Word:</label><br>
  <input type="text" id="word" name="word" value={{ word }}><br><br>
  <input type="submit" value="Submit">
</form>
</body>
</html>

结构体

app/
├─ app.py
├─ templates/
│  ├─ word.html

当我单击提交按钮时,浏览器实际上会加载提交 url 并显示“null”。有什么办法可以让浏览器不加载提交页面。这甚至是正确的方法吗?

谢谢,克里斯

标签: pythonhtmlbrowserfastapi

解决方案


我找到了一种通过使用隐藏的 iframe 来保持原始页面加载的方法......

<!DOCTYPE html>
<html>
<head>
<title>Word page</title>
</head>
<body>
<form action="/submit" method="post" target="frame>
  <label for="word">Word:</label><br>
  <input type="text" id="word" name="word" value={{ word }}><br><br>
  <input type="submit" value="Submit">
</form>
<iframe name="frame" style="display:none;"></iframe>
</body>
</html>

推荐阅读