본문 바로가기
내일배움캠프 미니프로젝트1/미니 프로젝트 개발일지

5월 9일 미니 팀과제 2일차

by seed0335 2023. 5. 9.

1일차 : 데이터 입력, 데이터 읽기 및 출력

2일차 : 데이터 삭제 (삭제 버튼을 누르면 출력된 데이터를 삭제하는 기능입니다.)

 

 

index.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">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
    integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
    integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM"
    crossorigin="anonymous"></script>

    <title>Document</title>

    <script>
        $(document).ready(function () {
            show_order();
        });
        function show_order() {
            fetch("/mars").then(res => res.json()).then(data => {
                let rows = data['result']
                rows.forEach((a) => {
                    let id = a['id']
                    let comment = a['comment']

                    // 데이터 삭제 기능 버튼 추가
                    let temp_html = `<p>ID : ${id} ---------- 관람평 : ${comment} 
                                    <button onclick ="del('${id}')">삭제</button></p>`
                    $('#page').append(temp_html)
                })
            })
        }
        
        function save() {
            let id = $('#id').val()
            let comment = $('#comment').val()

            let formData = new FormData()
            formData.append("id_give", id)
            formData.append("comment_give", comment)

            fetch("/test", { method: "post", body: formData }).then(res => res.json()).then(data => {
            alert(data['msg'])})
        }

        // 데이터 삭제 기능 !!!!!!!
        function del(a) {
            let formData = new FormData()
            let id1 = a
            formData.append("id_del", id1)

            fetch("/del", { method: "post", body: formData }).then(res => res.json()).then(data => {
                alert(data['del'])
                })
        }
    </script>
</head>
<body>
    <form method="get">
        <label for="id">아이디 : </label>
        <input type="text" id="id" name="id">
        <label for="comment">관람평 : </label>
        <input type="text" id="comment" name="comment"><br>
        <button onclick="save()">등록</button>
    </form>
    <p id = "page">

    </p>

</body>

</html>

 

app.py

프론트엔드로 데이터 받아서 맞는 데이터를 삭제 합니다. 

from flask import Flask, render_template, request, jsonify
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('mongodb+srv://sparta:test@cluster0.rsr8xyc.mongodb.net/?retryWrites=true&w=majority')
db = client.dbsparta

@app.route('/')
def home():
    return render_template('index.html')

#데이터 받기
@app.route("/test", methods=["post"])
def test_post():
   id_receive = request.form['id_give']
   comment_receive = request.form['comment_give']
   doc = {
       'id': id_receive,
       'comment' : comment_receive
   }
   db.comment.insert_one(doc)
   return jsonify({'msg': '저장완료'})

#데이터 보내기
@app.route("/mars", methods=["GET"])
def web_mars_get():
    comment_data = list(db.comment.find({},{'_id':False}))
    return jsonify({'result': comment_data})

#삭제기능
@app.route("/del", methods=["post"])
def del_get():
    id_receive = request.form['id_del']
    db.comment.delete_one({'id':id_receive})
    return jsonify({'del': '삭제 성공'})

if __name__ == '__main__':
    app.run('0.0.0.0',port=5000,debug=True)

댓글