我已经创建了一个fastapi Python服务器,它有两个端点。它们都呈现不同的HTML模板。但第一个模板是成功渲染,第二个也成功渲染时,提交按钮被点击。但当第二个模板上的后退按钮被点击,然后第一个模板不呈现
FastAPI服务器:-
from fastapi import FastAPI , Request , Response
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
templetes = Jinja2Templates(directory="templetes")
@app.get("/test")
async def test(request : Request):
data = {
"name" : "John",
"dob" : "31-3-230"
}
return templetes.TemplateResponse("result.html" , {"request" : request , "data":data})
class InputData(BaseModel):
name : str
date : str
@app.post("/result")
async def get_result(request : Request , input : InputData):
data = {
"name" : input.name,
"dob" : input.date
}
print(data)
return templetes.TemplateResponse("result.html" , {"request" : request , "data":data})
@app.get("/")
async def root(request : Request):
return templetes.TemplateResponse("form.html" , {"request" : request})
第一模板- Form.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Entry Form</title>
</head>
<body> <input id="first" type="text"> <input id="dob" type="date"> <button type="button"
onclick="submit()">Submit</button>
<script>function submit() { const name = document.getElementById("first").value; console.log(name) const date = document.getElementById("dob").value; console.log(date) fetch("/result", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: name, date: date }) }).then(response => response.text()).then(html => { document.getElementsByTagName("html")[0].innerHTML = html console.log(html); }) }</script>
<div id="result"></div>
</body>
</html>
第二个模板- result.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Result</title>
</head>
<body>
<p>Your Name is :{{data.name}}</p>
<p>Your Date of Birth is :{{data.dob}}</p>
<script>function displayHTML() { console.log("hello"); fetch("/", { method: "GET" }).then(response => response.text()).then(html => { document.getElementsByTagName("html")[0].innerHTML = html; }); } window.displayHTML = displayHTML; </script>
<button onclick="displayHTML()">Back</button>
</body>
</html>
我想在浏览器的同一窗口中显示第二页,以代替提交按钮上的第一页,并在第二页上单击返回按钮的第一页。
谁能帮帮我!
1条答案
按热度按时间wvt8vs2t1#
我发现了错误,我没有添加JavaScript代码到一个单独的JS文件,并放置在静态文件夹.添加JS代码后,单独的文件和链接到模板和服务器的文件,一切都工作正常