SQL & 웹 개발 숙제

웹개발 4주차 숙제코딩

김민커 2023. 5. 1. 20:59

스파르타피디아에 별점을 넣는 기능을 추가해 봅시다! 

 

먼저 파이썬 서버에 star 를 받는다.

def movie_post():
    url_receive = request.form['url_give']
    comment_receive = request.form['comment_give']
    star_receive = request.form['star_give']

그리고 document에 star를 넣고 insert 한다.

doc ={
        'title':ogtitle,
        'desc':ogdesc,
        'image':ogimage,
        'comment':comment_receive,
        'star':star_receive
    }
    db.movies.insert_one(doc)

index_html에  star가 들어가는 ID를 찾는다.

<div class="input-group mb-3">
            <label class="input-group-text" for="inputGroupSelect01">별점</label>
            <select class="form-select" id="star">

그리고 fetch로 데이터를 서버로 보낸다.

 function posting() {
            let url=$('#url').val()
            let comment=$('#comment').val()
            let star=$('#star').val()

            let formData = new FormData();
            formData.append("url_give", url);
            formData.append("comment_give", comment);
            formData.append("star_give", star);

            fetch('/movie', { method: "POST", body: formData }).then((res) => res.json()).then((data) => {
             
                alert(data['msg'])
                window.location.reload()
            })
        }

이제 star의 데이터가 데이터베이스에 저장이 되어있다.

fetch로 전달 받은 데이터로 인해  'GET'의 방식으로 서버의 데이터를 전달해준다.

@app.route("/movie", methods=["GET"])
def movie_get():
    all_movies = list(db.movies.find({},{'_id':False}))
    return jsonify({'result':all_movies})

마지막으로 서버의 데이터 리스트를 forEach 로 반복해서 출력한다.

   function listing() {
            fetch('/movie').then((res) => res.json()).then((data) => {
                let rows = data['result']
                $('#cards-box').empty()
               rows.forEach((a)=>{
                 let comment=a['comment']
                 let title=a['title']
                 let desc=a['desc']
                 let image=a['image']
                 let star =a['star']

                 let star_repeat='⭐'.repeat(star)

                 let temp_html = `<div class="col">
                                    <div class="card h-100">
                                     <img src="${image}"
                                                  class="card-img-top">
                                     <div class="card-body">
                                       <h5 class="card-title">${title}</h5>
                                          <p class="card-text">${desc}</p>
                                             <p>${star_repeat}</p>
                                                 <p class="mycomment">${comment}</p>
                                      </div>
                                     </div>
                                 </div>`
                 $('#cards-box').append(temp_html)
               })
             
            })