首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >FastAPI -使用Jquery - AJAX - PUT方法不起作用

FastAPI -使用Jquery - AJAX - PUT方法不起作用
EN

Stack Overflow用户
提问于 2020-12-23 14:27:50
回答 2查看 1.9K关注 0票数 0

日安。我正在学习FastAPI --并且做一个非常简单的CRUD应用--在前端使用Javascript,在后端使用FastAPI。所有路由都使用正常的localhost/docs swagger docs工作。我在前端使用jquery和AJAX。

我已连接postgresql数据库

到目前为止,POST方法工作得很好-在前端更新数据库和显示。

我已经创建了2个表单updateForm: 1-创建方法(POST) - works fine - myForm 2- update方法(PUT) - not working -div(静态无切换等)

前端的逻辑是,当我单击编辑按钮(使用jquery)时,我会在updateForm中显示数据--这部分正在工作。因为我能够通过控制台记录数据并查看返回的所有内容。

然而,当我想在更新文章按钮(点击)上发布(即使用PUT)方法时,服务器会发送一个响应200ok--但数据库中没有更新任何数据。

我希望能得到一些帮助--在过去的两天里...

index.html

代码语言:javascript
复制
{% extends 'layout.html' %} {% include 'header.html' %} {% block title %} Home {% endblock %} {% block body %}
<script type="text/javascript">
    $(document).ready(function() {
        var id;
        var title;
        var description;

        $("#add_button").click(function() {

            title = $("#title").val();
            description = $("#description").val();

            $.ajax({
                url: "/notes",
                type: "post",
                dataType: "json",
                contentType: "application/json",
                data: JSON.stringify({
                    title: title,
                    description: description
                }),

            }).then(setTimeout(location.reload.bind(location), 200));
        });

        $(".edit_button").click(function(id) {

            id = this.id;

            $.ajax({
                url: "/notes/" + id,
                type: "get",
                dataType: "json",
                contentType: "application/json",
                success: function(data) {
                    $($("#updateForm")[0].update_id).val(data.id);
                    $($("#updateForm")[0].updatetitle).val(data.title);
                    $($("#updateForm")[0].updatedescription).val(data.description)

                    console.log(data)

                },

            });
        });
        $(".update_button").click(function(id) {
            id = this.id

            $.ajax({
                url: "/notes/" + id,
                type: "patch",
                dataType: "json",
                contentType: "application/json",
                success: function(data) {
                    console.log("success");
                },

            });
        });
    });
</script>


<div class="container">
    <div class="row">
        <div class="col md-12">
            <div class="jumbotron">
                <form class="row g-3 mb-5 mt-1" id="myForm">
                    <div class="col-4">
                        <label for="title" class="visually-hidden">Article Title</label>
                        <input name="title" type="" class="form-control" id="title" placeholder="title">
                    </div>
                    <div class="col-4">
                        <label for="description" class="visually-hidden">Article Description</label>
                        <input name="description" type="" class="form-control" id="description" placeholder="description">
                    </div>

                    <div class="col-4 mt-2">
                        <button id="add_button" type="submit" class="btn btn-primary mt-4">Add Article</button>
                    </div>

                </form>
                <form class="row g-3 mb-5 mt-1" id="updateForm">
                    <div class="col-3">
                        <label for="updatetitle" class="visually-hidden">ID</label>
                        <input name="update_id" type="" class="form-control update_id" id="update_id">
                    </div>
                    <div class="col-3">
                        <label for="updatetitle" class="visually-hidden">Title</label>
                        <input name="updatetitle" type="" class="form-control updatetitle" id="updatetitle">
                    </div>
                    <div class="col-3">
                        <label for="updatedescription" class="visually-hidden">Description</label>
                        <input name="updatedescription" type="" class="form-control updatedescription" id="updatedescription">
                    </div>

                    <div class="col-3 mt-2">
                        <button id="update_button" type="submit" class="btn btn-primary mt-4" onsubmit="True">Update Article</button>
                    </div>

                </form>


                <table class="table" id="data_table">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Description</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        {%for note in notes%}
                        <tr>
                            <td>{{note.id}}</td>
                            <td>{{note.title}}</td>
                            <td>{{note.description}}</td>
                            <td>
                                <a class="btn btn-warning btn-xs edit_button" id="{{note.id}}">Edit</a>
                                <a class="btn btn-danger btn-xs delete_button" id="{{note.id}}">Delete</a>
                            </td>
                        </tr>
                        {%endfor%}
                    </tbody>

                </table>
            </div>
        </div>
    </div>
</div>




{% endblock %}

main.py

代码语言:javascript
复制
from fastapi import FastAPI
from typing import List, Dict, Any

from fastapi import Depends, FastAPI, HTTPException, Request, Response, Form
from fastapi.encoders import jsonable_encoder
from fastapi.responses import HTMLResponse
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.orm import Session
from fastapi.templating import Jinja2Templates

from . import crud, models, schemas
from .database import SessionLocal, engine

models.Base.metadata.create_all(bind=engine)



app = FastAPI()
templates = Jinja2Templates(directory="templates")

app.add_middleware(
    CORSMiddleware,
    allow_credentials = True,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


#original function
# @app.get("/notes", response_model=List[schemas.Note])
# def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
#     notes = crud.get_notes(db=db, skip=skip, limit=limit)
#     return notes

# STEP 1 - HOMEPAGE DISPLAY ALL DATA FUNCTION - WORKING
@app.get("/", response_class=HTMLResponse)
def read_notes(request: Request, skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    notes = crud.get_notes(db=db, skip=skip, limit=limit)
    return templates.TemplateResponse("index.html", {
        "request": request,
        "notes": notes,
    })


@app.post("/notes", response_model=schemas.Note, status_code=201)
def create_note(note: schemas.NoteCreate, db: Session = Depends(get_db)):
    return crud.create_note(db=db, note=note)



@app.get("/notes/{note_id}", response_model=schemas.Note)
def read_user(note_id: int, db: Session = Depends(get_db)):
    db_note = crud.get_note(db=db, note_id=note_id)
    if db_note is None:
        raise HTTPException(status_code=404, detail="Note not found")
    return db_note


@app.put("/notes/{note_id}", response_model=schemas.Note, status_code=200)
async def put_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
    db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
    crud.update_note(db=db, note=db_note)

@app.patch("/notes/{note_id}", response_model=schemas.Note, status_code=200)
async def patch_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
    print(note_id)
    print(note.title)
    print(note.description)
    db_note = schemas.Note(id = note_id, title= note.title, description=note.description)
    crud.update_note(db=db, note=db_note)

@app.delete("/notes/{note_id}", status_code=204)
async def delete_note(note_id: int, db: Session = Depends(get_db)):
    return crud.delete_note(db=db, note_id=note_id)

if __name__ == '__main__':
    uvicorn.run("main:app", host="127.0.0.1", port=8000)

schemas.py

代码语言:javascript
复制
from typing import List, Optional
from pydantic import BaseModel


class NoteBase(BaseModel):
    title: str
    description: str


class NoteCreate(NoteBase):
    pass

class Note(NoteBase):
    id: int

    class Config:
        orm_mode = True

models.py

代码语言:javascript
复制
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import relationship

from .database import Base

class Note(Base):
    __tablename__ = "notes"
    id = Column(Integer, primary_key=True, index=True)
    title = Column(String, nullable=True, default="new")
    description = Column(String, nullable=True, default="new")

crud.py

代码语言:javascript
复制
from sqlalchemy.orm import Session

from . import models, schemas


def get_note(db: Session, note_id: int):
    return db.query(models.Note).filter(models.Note.id == note_id).first()

def delete_note(db: Session, note_id: int):
    db_note = db.query(models.Note).filter(models.Note.id == note_id).first()
    db.delete(db_note)
    db.commit()
    return {}

def get_notes(db: Session, skip: int = 0, limit: int = 100):
    return db.query(models.Note).offset(skip).limit(limit).all()


def create_note(db: Session, note: schemas.NoteCreate):
    db_note = models.Note(title=note.title, description=note.description)
    db.add(db_note)
    db.commit()
    db.refresh(db_note)
    return db_note

def update_note(db: Session, note: schemas.Note):
    db_note = db.query(models.Note).filter(models.Note.id == note.id).first()
    db_note.title = note.title
    db_note.description = note.description
    db.commit()
    db.refresh(db_note)
    return db_note
EN

回答 2

Stack Overflow用户

发布于 2021-01-03 09:00:50

我认为你提供的代码只有两个小问题。

第一

在index.html中,当单击编辑按钮时,您正在发出get请求。相反,您应该创建一个postput。您可以分别使用type: "post"或put来完成此操作。

index.html

函数$(“.edit_button”).click(

( id ){id= this.id;$.ajax({ url:"/notes/“+ id,type:"get",//将其更改为post或put dataType:"json",contentType:”contentType/json“,成功: function(data) { $($("#updateForm").update_id).val(data.id);$($("#updateForm").updatetitle).val(data.title);$($("#updateForm").updatedescription).val(data.description) },});});

第二

在main.py中,您的put_note和patch_note路由都不返回任何内容。您希望返回更新后的模型。

main.py

代码语言:javascript
复制
@app.put("/notes/{note_id}", response_model=schemas.Note, status_code=200)
async def put_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
    db_note = schemas.Note(id = note_id, title= note.title, description=note.description)

    return crud.update_note(db=db, note=db_note) # Added return

@app.patch("/notes/{note_id}", response_model=schemas.Note, status_code=200)
async def patch_note(note_id: int, note: schemas.NoteCreate, db: Session = Depends(get_db)):
    print(note_id)
    print(note.title)
    print(note.description)
    db_note = schemas.Note(id = note_id, title= note.title, description=note.description)

    return crud.update_note(db=db, note=db_note) # Added return
票数 0
EN

Stack Overflow用户

发布于 2021-09-15 05:55:48

问题出在您的ajax调用上。修改update_button点击函数

代码语言:javascript
复制
        $(".update_button").click(function(id) {
        id = this.id

        $.ajax({
            url: "/notes/" + id,
            type: "patch",
            dataType: "json",
            contentType: "application/json",
            success: function(data) {
                console.log("success");
            },

        });
    });

代码语言:javascript
复制
    $("#update_button").click(function() {
    //        id = this.id
    id = $("#update_id").val();
    updatetitle = $("#updatetitle").val();
    updatedescription = $("#updatedescription").val();

    $.ajax({
        url: "/notes/" + id,
        type: "put",
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({
            id: id,
            title: updatetitle,
            description: updatedescription
            }),
        success: function(data) {
            console.log("success",data);
        },
        error: function() {
            console.log("error", data);
            alert('error loading from database...');
            }
    });
  });

它会工作的..。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65419931

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档