스파르타코딩 왕초보 시작반 4주차 내용(4-1 ~ 4-16) with jQuery

flask 사용해보기, HTTP request with jQuery

목표 : 주문 버튼을 누르면 주문자 목록이 추가되는 기능 만들기

중요하다고 느낀 기술 : HTTP request

흐름 :

1) 클라이언트 측에서 주문서를 작성하여 주문하기 버튼을 누른다.

2) 버튼에 있던 onclick 함수가 작동한다. 이 함수는 POST 메서드로 백엔드 단에 object 형태의 데이터를 전송한다.

        function order() {
            const name = $('#order-name').val();
            let count = $('#order-count').val();
            let address = $('#order-address').val();
            let phone = $('#order-phone').val();
            // 주문하기 API 연결
          	$.ajax({
                type: "POST",
                url: "/order",
                data: {name_give: name, count_give: count, address_give: address, phone_give: phone}, //여기서 백엔드로 전송!
                success: function (response) { // 성공하면
                    alert(response["msg"]);
                    window.location.reload();

                }
            })
        }

3) 백엔드 단에 있던 POST 메서드가 프론트 단에서 전송된 정보를 받아 작동한다. 백엔드에서는 object 형태의 데이터를 추출하여 새로운 오브젝트로 만들고, 이를 db에 저장한다.

@app.route('/order', methods=['POST'])
def save_order():
    name_receive = request.form['name_give']
    count_receive = request.form['count_give']
    address_receive = request.form['address_give']
    phone_receive = request.form['phone_give']

    doc = {
        'name': name_receive,
        'count': count_receive,
        'address': address_receive,
        'phone': phone_receive
    }

    db.ordersjq.insert_one(doc)
    return jsonify({'msg': '주문 성공!'}) #성공 메세지를 프론트로!

4.5) 성공 메세지를 백엔드에서 받게되면 프론트엔드에서 success 파트를 실행한다.

        function order() {
            const name = $('#order-name').val();
            let count = $('#order-count').val();
            let address = $('#order-address').val();
            let phone = $('#order-phone').val();
            // 주문하기 API 연결
          	$.ajax({
                type: "POST",
                url: "/order",
                data: {name_give: name, count_give: count, address_give: address, phone_give: phone}, 
                success: function (response) { // 성공하면
                    alert(response["msg"]); //응답의 메세지 알림
                    window.location.reload(); //창 새로고침

                }
            })
        }

4) onclick 함수에 있던 새로고침 함수에 의해 페이지가 새로고침 되고, 프론트 단에 ready로 걸려있던 GET 함수가 작동한다. (사실 항상 작동되고 있었지만, 데이터 베이스에 자료가 있을 때 결과가 나타난다.)

        $(document).ready(function () {
			function order_listing() {
            // 주문목록 보기 API 연결

						$.ajax({
                type: "GET",
                url: "/order",
                data: {}, //여기서 백엔드와 통신!
                success: function (response) {
                    if (response['result'] == 'success') {
                        const orders = response['orders'];
                        for (let i = 0; i < orders.length; i++) {
                            const name = orders[i]['name'];
                            const count = orders[i]['count'];
                            const address = orders[i]['address'];
                            const phone = orders[i]['phone'];

                            const temp_html = `<tr>
                                                <th scope="row">${name}</th>
                                                <td>${count}</td>
                                                <td>${address}</td>
                                                <td>${phone}</td>
                                            </tr>`

                            $('#orders-box').append(temp_html);
                        }
                    }
                }
            })
        }
        });

5) 백엔드 단에 있던 GET 메서드가 작동한다. 데이터 베이스에 저장된 모든 주문자의 정보를 오브젝트 형태로 만들어서 json 형태로 리턴한다.

@app.route('/order', methods=['GET'])
def view_orders():
    orders = list(db.ordersjq.find({}, {'_id': False}))
    return jsonify({'result': 'success', 'orders': orders}) #다시 프론트 success로 전송!

6) 모든 주문자의 정보를 for 문을 돌면서 프론트에서 결과를 보여준다.

결론 : HTTP request를 통해 클라이언트와 서버는 정보를 주고 받는다.

중요한 것 : 주소와 method가 일치할 때 서로 필요한 정보를 주고 받는다.

+)flask는 왜 쓰는 것이며, 무슨 장점을 가지고 있는걸까?
+)bs4로는 패키지 다운안되고, BeautifulSoup4로 받으면 받아짐, 또 다른 패키지는 잘 받아짐 도대체 왜????

좋은 웹페이지 즐겨찾기