您需要使用 Javascript 接口/库,例如获取API https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API,它允许您发送数据JSON
格式(示例如下)。用于提交Form https://fastapi.tiangolo.com/tutorial/request-forms/相反,看看数据这个答案 https://stackoverflow.com/a/71665594/17865804,同时发布两者Files
and Form
/JSON
数据,看一下这个答案 https://stackoverflow.com/a/70640522/17865804.
对于前端,您可以使用Jinja2Templates https://fastapi.tiangolo.com/advanced/templates/渲染并返回TemplateResponse
其中包括你的HTML
/JS
代码等。您可以使用 HTMLform
提交您的数据,然后获得form-data
转换成JSON
,如上所述here https://stackoverflow.com/questions/41431322/how-to-convert-formdata-html5-object-to-json。否则,您可以发布您的JSON
直接数据,如图here https://stackoverflow.com/questions/29775797/fetch-post-json-data/29823632-例如,body: JSON.stringify({name: "foo", roll: 1})
.
app.py
from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from pydantic import BaseModel
app = FastAPI()
templates = Jinja2Templates(directory="templates")
class Item(BaseModel):
name: str
roll: int
@app.post("/")
async def create_item(item: Item):
return item
@app.get("/")
async def index(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
模板/索引.html
<!DOCTYPE html>
<html>
<body>
<h1>Post JSON Data</h1>
<form method="post" id="myForm">
name : <input type="text" name="name" value="foo">
roll : <input type="number" name="roll" value="1">
<input type="button" value="Submit" onclick="submitForm()">
</form>
<div id="responseArea"></div>
<script>
function submitForm() {
var formElement = document.getElementById('myForm');
var data = new FormData(formElement);
fetch('/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(Object.fromEntries(data))
})
.then(resp => resp.text()) // or, resp.json(), etc.
.then(data => {
document.getElementById("responseArea").innerHTML = data;
})
.catch(error => {
console.error(error);
});
}
</script>
</body>
</html>