python - 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”。有什么办法可以让浏览器不加载提交页面。这甚至是正确的方法吗?
谢谢,克里斯
解决方案
我找到了一种通过使用隐藏的 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>
推荐阅读
- flutter - Flutter sql有时会两次保存产品
- javascript - 如何用新的键值重构 JSON 对象?
- javascript - 如何创建默认状态/清除容器并使用 HTML/CSS/JS 替换为新项目
- javascript - Chartjs 背景颜色多个数据集
- amazon-web-services - 无法通过 SSH 连接 AWS EC2 实例
- tensor - 压缩图像张量
- javascript - 无法将 undefined 或 null 转换为对象打字稿
- flutter - 颤振中是否有任何库或小部件可用于制作像附加的 gif 这样的小部件
- sdk - 如何将 expo sdk 版本从 42 降级到 40.0.1?
- css - SCSS 未在故事书中编译为 css