33_4주차 숙제_원페이지 쇼핑몰 완성하기*

49391 단어 jquerypythonjquery

서버와 클라이언트의 역할에 대해 조금 더 이해해 보기*

1주차에 완성한 쇼핑몰을 완성해주세요!

쇼핑몰은 두 가지 기능을 수행해야 합니다.

1) 주문하기(POST): 정보 입력 후 '주문하기' 버튼클릭 시 주문목록에 추가
2) 주문내역보기(GET): 페이지 로딩 후 하단 주문 목록이 자동으로 보이기

  • dbprac.py
from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

# insert / find / update / delete

# 저장 - 예시
doc = {'name':'bobby','age':21}
db.users.insert_one(doc)

# 한 개 찾기 - 예시
user = db.users.find_one({'name':'bobby'})

# 여러개 찾기 - 예시 ( _id 값은 제외하고 출력)
same_ages = list(db.users.find({'age':21},{'_id':False}))

# 바꾸기 - 예시
db.users.update_one({'name':'bobby'},{'$set':{'age':19}})

# 지우기 - 예시
db.users.delete_one({'name':'bobby'})
  • app.py
from flask import Flask, render_template, jsonify, request
app = Flask(__name__)

from pymongo import MongoClient
client = MongoClient('localhost', 27017)
db = client.dbsparta

## HTML을 주는 부분
@app.route('/')
def home():
    return render_template('index.html')

# API 역할을 하는 부분
@app.route('/order', methods=['POST'])
def order_info():
   name_receive = request.form['name_give']
   qtt_receive = request.form['qtt_give']
   address_receive = request.form['address_give']
   tel_receive = request.form['tel_give']

   doc = {
      'name': name_receive,
      'qtt': qtt_receive,
      'address': address_receive,
      'tel': tel_receive
   }
   db.dollorder.insert_one(doc)

   return jsonify({'msg': '주문이 완료되었습니다!'})

@app.route('/order', methods=['GET'])
def read_info():
   infos = list(db.dollorder.find({}, {'_id': False}))
   return jsonify({'all_infos': infos})

if __name__ == '__main__':
    app.run('0.0.0.0', port=5000, debug=True)
  • index.html
<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
          integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
            integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
            crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
            integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
            crossorigin="anonymous"></script>

    <title>어몽어스 인형 판매</title>
    <link href="https://fonts.googleapis.com/css2?family=Do+Hyeon&display=swap" rel="stylesheet">

    <style>
        * {
            font-family: 'Do Hyeon', sans-serif;
        }

        .myimg {
            background-color: green;

            width: 600px;
            height: 600px;

            background-image: url("https://cdn.shopify.com/s/files/1/0508/1828/5750/products/Official-Fully-Licensed-Among-Us-Orange-Plush-Doll-Among-Us-Plush-30cm-2.jpg?v=1636120807");
            background-size: cover;
            background-position: center;
        }

        .wrap {
            width: 600px;
            margin: auto;
        }

        .padding {
            padding: 20px 0px 0px;
        }

        .price {
            font-size: medium;
        }

        .mybtn {
            margin: auto;
            display: block;
        }

        .rate {
            color: blue;
        }
    </style>

    <script>
        $(document).ready(function () {
            q1();
            showOrder();
        });

        function q1() {
            $.ajax({
                type: "GET",
                url: "https://api.manana.kr/exchange/rate.json",
                data: {},
                success: function (response) {
                    let rate = response[1]['rate']
                    $("#rate-q1").text(rate);
                }
            })
        }

        function makeOrder() {
            let name = $('#name').val()
            let qtt = $('#qtt').val()
            let address = $('#address').val()
            let tel = $('#tel').val()

            $.ajax({
                type: "POST",
                url: "/order",
                data: {name_give:name, qtt_give:qtt, address_give:address, tel_give:tel},
                success: function (response) {
                    alert(response["msg"]);
                    window.location.reload();
                }
            })
        }

        function showOrder() {
            $.ajax({
                type: "GET",
                url: "/order",
                data: {},
                success: function (response) {
                    let infos = response['all_infos']
                    for(let i = 0; i < infos.length; i++) {
                        let name = infos[i]['name']
                        let qtt = infos[i]['qtt']
                        let address = infos[i]['address']
                        let tel = infos[i]['tel']

                        let temp_html = `<tr>
                                            <td>${name}</td>
                                            <td>${qtt}</td>
                                            <td>${address}</td>
                                            <td>${tel}</td>
                                        </tr>`

                        $('#infos-box').append(temp_html)
                    }
                }
            })
        }
    </script>
</head>

<body>
    <div class="wrap">

        <div class="myimg">
        </div>

        <!--    <h1>어몽어스 인형</h1>-->
        <h1 class="padding">어몽어스 인형
            <span class="price">가격: 3,000원 / 개</span>
        </h1>
        <p>이 상품은 신선한 주황색 어몽어스 인형입니다. 작고 동글동글하며 머리에 치즈를 얹은 모양은 누구에게나 귀여움을 살 것입니다.
            인형의 겉을 감싸는 재질은 부드러운 폴리에스테르로, 손끝의 감각에 편안함을 가져다 줄 것입니다.
            인형이 당신의 모든 생각을 알아차리지는 못하겠지만, 당신 옆에 우두커니 있을 것이니, 귀여워해 주세요.
        </p>

        <p class="rate">
            달러-원 환율 : <span id="rate-q1">  </span>
        </p>

        <h1 class="padding">주문하기</h1>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text">주문자 이름</span>
            </div>
            <input type="text" class="form-control" placeholder="" aria-label="Username"
                   aria-describedby="basic-addon1" id="name">
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <label class="input-group-text" for="qtt">수량</label>
            </div>
            <select class="custom-select" id="qtt">
                <option selected>수량을 선택하세요</option>
                <option value="10">10</option>
                <option value="20">20</option>
                <option value="30">30</option>
            </select>
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text" >주소</span>
            </div>
            <input type="text" class="form-control" placeholder="" aria-label="Username"
                   aria-describedby="basic-addon1" id="address">
        </div>
        <div class="input-group mb-3">
            <div class="input-group-prepend">
                <span class="input-group-text">전화번호</span>
            </div>
            <input type="text" class="form-control" placeholder="" aria-label="Username"
                   aria-describedby="basic-addon1" id="tel">
        </div>

        <button onclick="makeOrder()" type="button" class="btn btn-primary mybtn">주문하기</button>
         <div class="reviews padding">
                <table class="table">
                    <thead>
                    <tr>
                        <th scope="col">주문자 이름</th>
                        <th scope="col">수량</th>
                        <th scope="col">주소</th>
                        <th scope="col">전화번호</th>
                    </tr>
                    </thead>
                    <tbody id="infos-box">


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

</body>

</html>

좋은 웹페이지 즐겨찾기