👉 output
📍 준비 사항
- MongoDB 로그인과 폴더 셋팅 및 서버 구축 관련(flask), mongoDB 관련(pymongo, dnspython, certifi) 패키지 설치
- 구현할 기능 : 팬명록 작성과 작성 리스트 보여주기
❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
④ 확인하기
① 클라이언트와 서버 연결 확인하기
app.py
실행해서 index.html
와의 연결 확인② 서버부터 만들기
app.py
파일에 DB 연결 및 데이터 추가 코드 기입@app.route("/fanrecord", methods=["POST"])
def fanrecord_post():
name_receive = request.form['name_give']
comment_receive = request.form['comment_give']
doc = {
'name' : name_receive,
'comment' : comment_receive
}
db.fanrecords.insert_one(doc)
return jsonify({'msg':'응원 완료!'})
③ 클라이언트 만들기
index.html
파일에 input에 기입되는 값을 데이터로 만든 후 app.py
파일과 연결 및 새로고침 기능 추가function save_comment(){
let name = $('#name').val()
let comment = $('#comment').val()
$.ajax({
type: 'POST',
url: '/fanrecord',
data: { name_give : name, comment_give : comment },
success: function (response) {
alert(response['msg'])
window.location.reload()
}
})
}
④ 확인하기
👉 output
❗️ 작업 순서
① 클라이언트와 서버 연결 확인하기
② 서버부터 만들기
③ 클라이언트 만들기
④ 확인하기
① 클라이언트와 서버 연결 확인하기
app.py
실행해서 index.html
와의 연결 확인(app.py
파일의 def web_homework_get():
부분과 index.html
파일의 ajax
get 부분)② 서버부터 만들기
app.py
파일에 데이터 가져오는 코드 기입@app.route("/fanrecord", methods=["GET"])
def fanrecord_get():
fan_list = list(db.fanrecords.find({}, {'_id' : False}))
return jsonify({'lists' : fan_list})
③ 클라이언트 만들기
index.html
파일에 로딩 시 DB의 리스트를 조건문으로 가져오고, DB 값을 태그 내 탬플릿으로 붙이기function show_comment(){
$.ajax({
type: "GET",
url: "/fanrecord",
data: {},
success: function (response) {
let rows = response['lists']
for (let i = 0; i < rows.length; i++) {
let name = rows[i]['name']
let comment = rows[i]['comment']
let temp_html = `<div class="card">
<div class="card-body">
<blockquote class="blockquote mb-0">
<p>${comment}</p>
<footer class="blockquote-footer">${name}</footer>
</blockquote>
</div>
</div>`
$('#comment-list').append(temp_html)
}
}
});
}
④ 확인하기